代码
用邻接表存储
bool TopologicalSort(Graph G) {
InitStack(S);
for (int i = 0; i < G.vexnum; i++) {
if (indegree[i] == 0) Push(S, i);
}
int count = 0;
while (!isEmpty(S)) {
Pop(S, i);
print[count++] = i;
for (p = G.Vertices[i].firstarc; p; p = p->nextarc) { //p为i对应的头指针,遍历i的所有的节点
v = p->adjvex;
if (!(--indegree[v])) Push(S, v);
}
}
if (count < G.vexnum) return false;
else return true;
}