三木社区

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 327|回复: 0
打印 上一主题 下一主题

C语言数据结构-algo7-4.c

[复制链接]

1562

主题

1564

帖子

4904

积分

博士

Rank: 8Rank: 8

积分
4904
跳转到指定楼层
楼主
发表于 2017-9-1 09:27:16 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
  1. /* algo7-4.c 输出有向图的一个拓扑序列。实现算法7.12的程序 */
  2. #include"c1.h"
  3. #define MAX_NAME 5 /* 顶点字符串的最大长度 */
  4. typedef int InfoType;
  5. typedef char VertexType[MAX_NAME]; /* 字符串类型 */
  6. #include"c7-2.h"
  7. #include"bo7-2.c"

  8. void FindInDegree(ALGraph G,int indegree[])
  9. { /* 求顶点的入度,算法7.12、7.13调用 */
  10.    int i;
  11.    ArcNode *p;
  12.    for(i=0;i<G.vexnum;i++)
  13.      indegree[i]=0; /* 赋初值 */
  14.    for(i=0;i<G.vexnum;i++)
  15.    {
  16.      p=G.vertices[i].firstarc;
  17.      while(p)
  18.      {
  19.        indegree[p->adjvex]++;
  20.        p=p->nextarc;
  21.      }
  22.    }
  23. }

  24. typedef int SElemType; /* 栈类型 */
  25. #include"c3-1.h"
  26. #include"bo3-1.c"
  27. Status TopologicalSort(ALGraph G)
  28. { /* 有向图G采用邻接表存储结构。若G无回路,则输出G的顶点的一个拓扑序列并返回OK, */
  29.    /* 否则返回ERROR。算法7.12 */
  30.    int i,k,count,indegree[MAX_VERTEX_NUM];
  31.    SqStack S;
  32.    ArcNode *p;
  33.    FindInDegree(G,indegree); /* 对各顶点求入度indegree[0..vernum-1] */
  34.    InitStack(&S); /* 初始化栈 */
  35.    for(i=0;i<G.vexnum;++i) /* 建零入度顶点栈S */
  36.      if(!indegree[i])
  37.        Push(&S,i); /* 入度为0者进栈 */
  38.    count=0; /* 对输出顶点计数 */
  39.    while(!StackEmpty(S))
  40.    { /* 栈不空 */
  41.      Pop(&S,&i);
  42.      printf("%s ",G.vertices[i].data); /* 输出i号顶点并计数 */
  43.      ++count;
  44.      for(p=G.vertices[i].firstarc;p;p=p->nextarc)
  45.      { /* 对i号顶点的每个邻接点的入度减1 */
  46.        k=p->adjvex;
  47.        if(!(--indegree[k])) /* 若入度减为0,则入栈 */
  48.          Push(&S,k);
  49.      }
  50.    }
  51.    if(count<G.vexnum)
  52.    {
  53.      printf("此有向图有回路\n");
  54.      return ERROR;
  55.    }
  56.    else
  57.    {
  58.      printf("为一个拓扑序列。\n");
  59.      return OK;
  60.    }
  61. }

  62. void main()
  63. {
  64.    ALGraph f;
  65.    printf("请选择有向图\n");
  66.    CreateGraph(&f);
  67.    Display(f);
  68.    TopologicalSort(f);
  69. }
复制代码


回复

使用道具 举报

Archiver|手机版|小黑屋|三木电子社区 ( 辽ICP备11000133号-4 )

辽公网安备 21021702000620号

GMT+8, 2025-5-12 01:04 , Processed in 0.026159 second(s), 23 queries .

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表