#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define MaxVertexNum 100
typedef struct
{
int *base;
int * top;
}sqstack;
void Init(sqstack & s)
{
s.base=(int *)malloc(sizeof(int)*MaxVertexNum);
if(!s.base)
cout<<"未分配到内存";
s.top=s.base;
}
void push(sqstack & s,int e)
{
*s.top=e;
s.top++;
}
void pop(sqstack & s,int & e)
{
if(s.top==s.base)
cout<<"栈空,操作错误";
s.top--;
e=*s.top;
}
typedef char VertexType;
typedef struct node //边表节点
{
int adjvex; //该边所对应的点的序号
struct node * next;
}EdgeNode;
typedef struct //顶点表节点
{
VertexType vertex;
EdgeNode* firstedge;
}VertexNode;
typedef VertexNode AdjList[MaxVertexNum];
typedef struct
{
AdjList adjlist;
int arcnum,vexnum;
}ALGraph;
void create(ALGraph & g)
{
int i,j,k,w,v;
EdgeNode * s;
//printf("读入顶点数和边数");
cout<<"读入顶点数和边数"<<endl;
cin>>g.vexnum>>g.arcnum;
cout<<"请输入各顶点的名称"<<endl;
for (i=0;i<g.vexnum;i++)
{
cin>>g.adjlist[i].vertex;
g.adjlist[i].firstedge=NULL;
}
cout<<"请输入各边的信息,按边的起始顶点,结束顶点输入"<<endl;
cout<<"读入(vi-vj)的顶点对序号"<<endl;
for (k=0;k<g.arcnum;k++)
{
//printf("读入(vi-vj)的顶点对序号");
//scanf("%d,%d",&i,&j);
cin>>i>>j;
s=(EdgeNode*)malloc(sizeof(EdgeNode));
s->adjvex=j;
s->next=g.adjlist[i].firstedge; //插入表头
g.adjlist[i].firstedge=s;
}
}
void find(ALGraph g,int indegree[MaxVertexNum])
{
int i;EdgeNode * p;
for(i=0;i<g.vexnum;i++)
indegree[i]=0;
for(i=0;i<g.vexnum;i++)
{
p=g.adjlist[i].firstedge;
while(p!=NULL)
{
indegree[p->adjvex]++;
p=p->next;
}
}
}
void TopoSort(ALGraph g)
{
sqstack s;
EdgeNode * p;
int indegree[MaxVertexNum ];
int i,count,k;
find(g,indegree);
Init(s);
for(i=0;i<g.vexnum;i++)
if(indegree[i]==0)
push(s,i);
count=0;
while(s.top!=s.base)
{
pop(s,i);
cout<<g.adjlist[i].vertex;
count++;
p=g.adjlist[i].firstedge;
while(p)
{
k=p->adjvex;
indegree[k]--;
if(indegree[k]==0)
push(s,k);
p=p->next;
}
}
if(count<g.vexnum)
cout<<"含有回路"<<endl;
else
cout<<"不含回路"<<endl;
}
void main()
{
ALGraph G;
create(G);
TopoSort(G);
}