预定义:
#define MVNum 1000
typedef char VerTexType;
typedef struct{
int array[MVNum];
int top;
}Stack;
typedef struct ArcNode{
int adjvex;
ArcNode *nextarc;
}ArcNode;
typedef struct VNode{
VerTexType data;
ArcNode *firstarc;
}VNode,AdjList[MVNum];
typedef struct{
AdjList vertices;
int vexnum, arcnum;
}ALGraph;
构造邻接链表:
//用于记录下标节点的入度。
int indegree[MVNum] = {0};
int LocateVex(AMGraph *G,VerTexType v){
for(int i=0;i<G->vexnum;i++){
if(G->vex[i]==v)
return i;
}
return -1;
}
int CreateGraph()
{
//初始化
ALGraph* G;
G->vexnum=x;
G->arcnum=x;
for(i = 0;i<G->vexnum;i++){
G->vertices[i].data=x;
G->vertices[i].firstarc=NULL;
}
for(k=0;k<G->arcnum;k++){
//v1(i)->v2(j)
i = LocateVex(G, v1);
j = LocateVex(G, v2);
//头插法
ArcNode p;
p->adjvex = j;
p->nextarc = G->vertices[i].firstarc;
G->vertices[i].firstarc = p;
//入度++
indegree[j]++;
}
}
拓扑排序算法:
bool TopologicalSort(Graph G){
InitStack(S);
//将所有入度为0的顶点入栈
for(int i=0;i<G.vexnum;i++)
if(indegree[i]==0)
Push(S,i);
//count记录已经输出的定点数
int count=0;
while(!Empty(S)){
//出栈
Pop(S,i);
print[count++];
//将所有t指向的顶点的入度减1,并且将入度减为0的顶点压入栈
for(p=G.vertices[i].firstarc;p;p=p->nextarc){
v=p->adjvex;
if(!(--indegree[v]))
Push(S,v);
}
}
//有回路
if(count<G.vexnum)
return false;
return true;
}