拓扑排序的过程:
1)从有向图中选择一个没有前驱的(即入度为0)结点并且输出它;
2)从网中删除该结点,并且删去从该顶点发出的全部有向边;
3)重复以上两步,知道剩余图中不再存在没有前驱的结点为止。
#define MAXV 255
#define ElemType char
typedef struct ArcNode
{
int agjvex;
struct ArcNode* nextarc;
int weight;
}ArcNode;
typedef struct VNode {
ElemType data;
int count; //存放顶点入度信息
ArcNode* firstarc;
}VNode;
typedef VNode AdjList[MAXV];
typedef struct {
AdjList adjlist;
int n, e; //结点数和边数
}AGraph;
//拓扑排序
int TopSort(AGraph* G, int Topsq[])
{
ArcNode* p;
int i, j, n = 0;
int st[MAXV]; //存放入度为0的结点
int top = -1;
for (i = 0; i < G->n; i++)
{
if (G->adjlist[i].count == 0) //将入度为0 的结入栈
{
top++;
st[top] = i;
}
while (top > -1) //栈不空
{
i = st[top]; //取栈顶结点
top--;
Topsq[n] = i; n++; //将其放入到拓扑序列中
p = G->adjlist[i].firstarc;
while (p != NULL)
{
j = p->agjvex;
G->adjlist[j].count--;
if (G->adjlist[j].count == 0) //如果该结点入度为0,将其入栈
{
top++ ;
st[top] = j;
}
p = p->nextarc;
}
}
if (n < G->n)
{
return 0;//拓扑排序不成功
}
else return 1;//拓扑排序成功
}
}