ALGraph.h
#ifndef ALGraph_H
#define ALGraph_H
const int MaxSize=10;
struct ArcNode
{
int adjvex;
ArcNode*next;
};
template <class DataType>
struct VertexNode
{ DataType in;
DataType vertex;
ArcNode *firstedge;
};
template<class DataType>
class ALGraph
{
public:
ALGraph(DataType a[],int n,int e);
void TopSort();
private:
VertexNode<DataType> adjlist[MaxSize];
int vertexNum,arcNum;
} ;
#endif
ALGraph.cpp
#include<iostream>
using namespace std;
#include"ALGraph.h"//引入说明
template<class DataType>
ALGraph<DataType>::ALGraph(DataType a[],int n,int e)
{ArcNode *s;
int i,j,k;
vertexNum=n;
arcNum=e;
for( i=0;i<vertexNum;i++)
{
adjlist[i].in=0;
adjlist[i].vertex=a[i];
adjlist[i].firstedge=NULL;}
for(k=0;k<arcNum;k++)
{
cin>>i>>j;
s=new ArcNode;
s->adjvex=j;//生成一个边表节点s
adjlist[j].in++;
s->next=adjlist[i].firstedge;//将节点s插入到第i个边表的表头
adjlist[i].firstedge=s;
}
}
template<class DataType>
void ALGraph<DataType>::TopSort()
{ int S[MaxSize];
ArcNode *p;
int i,j,k;
int top=-1;
int count=0;
for(int i=0;i<vertexNum;i++)
if(adjlist[i].in==0)
S[++top]=i;
while(top!=-1)
{
j=S[top--];
cout<<adjlist[j].vertex;
count++;
p=adjlist[j].firstedge;
while(p!=NULL)
{
k=p->adjvex;
adjlist[k].in--;
if(adjlist[k].in==0)
S[++top]=k;
p=p->next;
}
}
if(count<vertexNum)
cout<<"有回路";
}
ALGraph_main.cpp
#include<iostream>
using namespace std;
#include"ALGraph.cpp"
int main()
{
char a[6]={'A','B','C','D','E','F'};
ALGraph<char>G(a,6,9);
G.TopSort();
return 0;
}