//拓扑排序_基于邻接表 //大纲:删除无前继结点的顶点 // //输入: // 先确定顶点数和边数 // 分为头结点和值结点,头结点含有count,用于计数这个结点当前含有的前继 // //输出拓扑排序: // 使用栈记录count为0的结点,栈空时结束 // 当count--后为0,说明这个结点的前继处理完了,把这个结点放入栈里 // 最后若还有值结点存在,说明存在环了 // // 6 8 0 1 0 2 0 3 1 4 2 4 2 5 3 4 3 5 032514Press any key to continue #include <iostream> using namespace std; typedef struct zhinode *zhinode_pointer; struct zhinode////////////值结点 { zhinode(){link=NULL;} int var; zhinode_pointer link; }; struct heapnode///////////头结点 { heapnode(){count=0;link=NULL;} int count; zhinode_pointer link; }; struct heapnode *draw();//绘图 void insert(struct heapnode *heap,int a,int b);//连接值结点 void deal(struct heapnode *heap);//输出拓扑排序 int v,edge; int main(int argc, char const *argv[]) { struct heapnode *heap=draw(); deal(heap); judge_loop(heap); return 0; } struct heapnode *draw()//绘图 { int i; int spot1,spot2; cin>>v>>edge;///输入点数目 struct heapnode *heap=new struct heapnode[v]; for (i = 0; i < edge; ++i) { cin>>spot1>>spot2; insert(heap,spot1,spot2); } return heap; } void insert(struct heapnode *heap,int a,int b) { heap[b].count++;//b的前继加1 zhinode_pointer ok=new struct zhinode;//增加值结点 if(ok==NULL)cerr<<"申请失败"; ok->var=b;//给值结点赋值 zhinode_pointer item=heap[a].link; if(item==NULL)heap[a].link=ok;//无链时 else{//////////////////////////有链时 zhinode_pointer dangqian=item; while(item) { dangqian=item; item=item->link; } dangqian->link=ok; } } ///-------------------------------------------------------------/// void deal(struct heapnode *heap) { int* zhan=new int[v]; int zhan_top=0; for (int i = 0; i < v; ++i) if(heap[i].count==0)zhan[zhan_top++]=i;//count为0时。进栈; if(zhan_top==0)cerr<<"error"; zhinode_pointer will_free; zhinode_pointer item; while(zhan_top!=0)//有开始结点 { will_free=heap[ zhan[--zhan_top] ].link;//要删除的值结点 cout<<zhan[zhan_top];//输出某个工程 while(will_free != NULL)//要删除的开始结点不为空 { item=will_free->link;//下一个值结点 if( !--heap[will_free->var].count )zhan[zhan_top++]=will_free->var;//当count为0时,说明前继处理完了,进栈。 delete will_free;//删除值结点 will_free=item; } } delete zhan; } void judge_loop(struct heapnode *heap) { for (int i = 0; i < v; ++i) { if (heap[i].count != 0) { cout<<"have loop"; } } }
原文:http://blog.csdn.net/h1023417614/article/details/19763853