拓扑排序_基于邻接表

//拓扑排序_基于邻接表
//大纲:删除无前继结点的顶点
//
//输入:
//   先确定顶点数和边数
//   分为头结点和值结点,头结点含有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)//处理后还有非0的count
		{
			cout<<"have loop";
		}
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

紫云的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值