设计算法,输出有向无环图G的拓扑序列。图采用邻接表存储。

本文介绍了一种基于邻接表的有向图拓扑排序算法实现。通过计算每个顶点的入度,并利用栈来存储当前没有前驱的顶点,从而实现了对有向图的拓扑排序。同时提供了创建邻接表的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下:(函数在本人其他文章都有,在这里只写函数部分,提供思路)


//------------------拓扑排序-------------------
int indegree[MAX];
void Find_indegree(ALG H,int indegree[])
{
	memset(indegree,0,sizeof(indegree));
	ArcNode *p;
	for(int i=1;i<=H.dian;i++)
	{
		if(H.toulist[i].firstarc)
		{
			for(p=H.toulist[i].firstarc;p;p=p->nextarc)
			{
				indegree[p->adddain]++;
			}
		}
	}
}
void Topsort(ALG H)
{
	int i;
	ArcNode *p;
	Find_indegree(H,indegree);
	Stack S;InitStack(S);
	for(i=1;i<=H.dian;i++)
	{
		if(!indegree[i])
			Push(S,i);
	}
	int count=0;
	while(!Isempty(S))
	{
		Pop(S,i);	printf("%c ",H.toulist[i].data); count++;
		for(p=H.toulist[i].firstarc;p;p=p->nextarc)
		{
			int k=p->adddain;
			if(!(--indegree[k]))
				Push(S,k);
		}
	}
	if(count<H.dian)
	{
		printf("该有向图有回路\n");
		return ;	
	}
}

//---------------邻接表---------------------- 
int locate_dian(ALG H,Diantype a)
{
	for(int i=1;i<=H.dian;i++)
	{
		if(H.toulist[i].data==a)
			return i;
	}
	return 0;
}
void Creat_ALG(ALG &H)
{//根据输入的有向图G的顶点数及边数,建立图G的邻接表
	printf("请输入点数和弧数\n");
	cin>>H.dian>>H.hu;
	getchar();
	printf("请输入节点信息\n");
	for(int i=1;i<=H.dian;i++)
	{
		cin>>H.toulist[i].data;
		H.toulist[i].firstarc=NULL;
	}
	getchar();
	printf("请输入%d条弧\n",H.hu);
	for(int k=1;k<=H.hu;k++)
	{
		Diantype x,y;
		int i,j;
		ArcNode *p,*node;
		cin>>x>>y;	getchar();
		i=locate_dian(H,x);j=locate_dian(H,y);
		//----i->j-------
		node=new ArcNode;
		node->adddain=j;	node->nextarc=NULL;
		p=H.toulist[i].firstarc;
		if(!p)
			H.toulist[i].firstarc=node;
		else
			{
				while(p->nextarc)
					p=p->nextarc;
				p->nextarc=node;
			}
		//----j->i--------
		/*node=new ArcNode;
		node->adddain=i;	node->nextarc=NULL;
		p=H.toulist[j].firstarc;
		if(!p)
			H.toulist[j].firstarc=node;
		else
		{
			while(p->nextarc)
				p=p->nextarc;
			p->nextarc=node;
		}
		*/
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值