#include "algraph_topo.h" #include "stdio.h" #include "stdlib.h" void createDN(algraph &g)...{} void createUDN(algraph &g)...{} void createUDG(algraph &g)...{} //locate the name vertice's index int locate(algraph g, char name)...{ for(int i =0; i < g.vexnum; i++)...{ if(name == g.vertex[i].data)...{ return i; } } return-1; } void createDG(algraph &g)...{ printf("input the number of vertex and arcs: "); scanf("%d %d", &g.vexnum, &g.arcnum); fflush(stdin); int i =0, j =0, k =0; printf("input the name of vertex: "); for(i =0; i < g.vexnum; i++)...{ scanf("%c", &g.vertex[i].data); fflush(stdin); g.vertex[i].firstarc = NULL; g.vertex[i].in_degree =0; } //construct the adjacent list char v1, v2; int w; ArcNode *p; printf("input the %d arcs v1 v2 and weight: ", g.arcnum); for(k =0; k < g.arcnum; k++)...{ scanf("%c %c %d", &v1, &v2, &w); fflush(stdin); i = locate(g, v1); j = locate(g, v2); //new a node p = (ArcNode *)malloc(sizeof(ArcNode)); p->adjvex = j; p->info = w; p->next = NULL; //insert the node in the head of list if(!g.vertex[i].firstarc)...{ g.vertex[i].firstarc = p; }else...{ p->next = g.vertex[i].firstarc; g.vertex[i].firstarc = p; } g.vertex[j].in_degree++; } } //print the list void printGraph(algraph g)...{ for(int i =0; i < g.vexnum; i++)...{ printf("%c's adjacent list is: ", g.vertex[i].data); ArcNode *p = g.vertex[i].firstarc; while(p)...{ printf("%c(%d) ", g.vertex[p->adjvex].data, p->info); p = p->next; } printf(""); } } void createGragh(algraph &g)...{ printf("please input the type of graph: "); scanf("%d", &g.kind); switch(g.kind)...{ case DG: createDG(g); //printGraph(g); break; case DN: createDN(g); break; case UDG: createUDG(g); break; case UDN: createUDN(g); break; } } //²éÕÒÏÂÒ»¸ö int findNext(algraph g)...{ for(int i =0; i < g.vexnum; i++)...{ if(g.vertex[i].in_degree ==0)...{ return i; } } return-1; } //topo order void topoSort(algraph g)...{ printf("the topo sort of graph is: "); for(int i =0; i < g.vexnum; i++)...{ int index = findNext(g); if(index >-1)...{ printf("%c ", g.vertex[index].data); //don't consider the vertice again g.vertex[index].in_degree =-1; ArcNode *p = g.vertex[index].firstarc; while(p)...{ g.vertex[p->adjvex].in_degree--; p = p->next; } }else...{ break; } } printf(""); } void main()...{ algraph g; createGragh(g); topoSort(g); }
程序的运行结果如下:
please input the type of graph: 0 input the number of vertex and arcs: 68 input the name of vertex: a b c d e f input the 8 arcs v1 v2 and weight: a d 1 a c 1 a b 1 c e 1 c b 1 d e 1 f e 1 f d 1 the topo sort of graph is: a c b f d e Press any key to continue