算法思路:
(1) 从有向图中选择一个没有前驱(入度为0)的顶点输出;
(2) 删除①中的顶点,并且删除从该顶点出发的全部边;
(3) 重复上述两步,直到剩余的图不存在没有前驱的顶点为止;
#define INF 0x3f3f3f3f #define maxSize 1005
typedef struct ArcNode{ int vex; //该边所指向的结点位置 struct ArcNode*nextarc; //指向下一条边的指针 }ArcNode;
typedef struct VNode{ int count; //顶点当前的入度 struct ArcNode*firstarc;//指向第一条边的指针 }VNode;
typedef struct LGraph{ int n,e; struct VNode adjlist[maxSize]; }LGraph;
int TopSort(LGraph*g) { int i,j,n=0; int stack[maxSize],top=-1; ArcNode*p; //将图中入度为0的顶点入栈 for(i=0;i<g->n;i++) if(g->adjlist[i].count==0) stack[++top]=i; //由该顶点引出的边所指向顶点的入度均-1 while(top!=-1) { i=stack[top--]; n++; cout<<i<<" "; p=g->adjlist[i].firstarc; while(p!=NULL) { j=p->vex; (g->adjlist[j].count)--; if(g->adjlist[j].count==0) stack[++top]=j; p=p->nextarc; } } if(n==g->n)return 1; else return 0; }