代码如下:(函数在本人其他文章都有,在这里只写函数部分,提供思路)
//------------------拓扑排序-------------------
int indegree[MAX];
void Find_indegree(ALG H,int indegree[])
{
memset(indegree,0,sizeof(indegree));
ArcNode *p;
for(int i=1;i<=H.dian;i++)
{
if(H.toulist[i].firstarc)
{
for(p=H.toulist[i].firstarc;p;p=p->nextarc)
{
indegree[p->adddain]++;
}
}
}
}
void Topsort(ALG H)
{
int i;
ArcNode *p;
Find_indegree(H,indegree);
Stack S;InitStack(S);
for(i=1;i<=H.dian;i++)
{
if(!indegree[i])
Push(S,i);
}
int count=0;
while(!Isempty(S))
{
Pop(S,i); printf("%c ",H.toulist[i].data); count++;
for(p=H.toulist[i].firstarc;p;p=p->nextarc)
{
int k=p->adddain;
if(!(--indegree[k]))
Push(S,k);
}
}
if(count<H.dian)
{
printf("该有向图有回路\n");
return ;
}
}
//---------------邻接表----------------------
int locate_dian(ALG H,Diantype a)
{
for(int i=1;i<=H.dian;i++)
{
if(H.toulist[i].data==a)
return i;
}
return 0;
}
void Creat_ALG(ALG &H)
{//根据输入的有向图G的顶点数及边数,建立图G的邻接表
printf("请输入点数和弧数\n");
cin>>H.dian>>H.hu;
getchar();
printf("请输入节点信息\n");
for(int i=1;i<=H.dian;i++)
{
cin>>H.toulist[i].data;
H.toulist[i].firstarc=NULL;
}
getchar();
printf("请输入%d条弧\n",H.hu);
for(int k=1;k<=H.hu;k++)
{
Diantype x,y;
int i,j;
ArcNode *p,*node;
cin>>x>>y; getchar();
i=locate_dian(H,x);j=locate_dian(H,y);
//----i->j-------
node=new ArcNode;
node->adddain=j; node->nextarc=NULL;
p=H.toulist[i].firstarc;
if(!p)
H.toulist[i].firstarc=node;
else
{
while(p->nextarc)
p=p->nextarc;
p->nextarc=node;
}
//----j->i--------
/*node=new ArcNode;
node->adddain=i; node->nextarc=NULL;
p=H.toulist[j].firstarc;
if(!p)
H.toulist[j].firstarc=node;
else
{
while(p->nextarc)
p=p->nextarc;
p->nextarc=node;
}
*/
}
}