数据结构 拓扑排序

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; 
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值