数据结构 拓扑排序

来源:互联网 发布:算法第四版目录 编辑:程序博客网 时间:2024/06/07 23:48

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



原创粉丝点击