反向邻接表

以p和q作为工作指针,p负责遍历原始邻接表,q用于创建反向邻接表的边结点。在遍历原始邻接表的过程中,反向邻接表的边界点就是一个由顶点i指向顶点p->node的边。

#include <iostream>
using namespace std;

struct ArcNode          //边表
{
	int node;           //所指向的顶点的序号
	ArcNode* next;
};

struct Vertex           //顶点表
{
	ArcNode* arc = NULL;    //指向的边
};

void build_adjacency_list(Vertex *&adjacency_list, int n)       //建立一个邻接表
{
	int a, b;
	ArcNode* p = NULL;
	adjacency_list = new Vertex[n];
	cin >> a >> b;
	while (a >= 0 && b >= 0)
	{
		p = new ArcNode;
		p->node = b;
		p->next = adjacency_list[a].arc;
		adjacency_list[a].arc = p;
		cin >> a >> b;
	}
}

Vertex* reverse_graph(Vertex adjancency_list[], int n)          //建立反向邻接表
{
	Vertex* adverse_adjancency_list = new Vertex[n];			//反向邻接表
	ArcNode* p = NULL, * q = NULL;
	for (int i = 0; i < n; i++)
	{
		p = adjancency_list[i].arc;								
		while (p != NULL)
		{
			q = new ArcNode;
			q->node = i;										//产生一个由顶点i指向顶点p->node的边
			q->next = adverse_adjancency_list[p->node].arc;
			adverse_adjancency_list[p->node].arc = q;
			p = p->next;
		}
	}
	return adverse_adjancency_list;
}

void traverse(Vertex adjancency_list[], int n)                  //遍历邻接表
{
	ArcNode* p = NULL;
	for (int i = 0; i < n; i++)
	{
		p = adjancency_list[i].arc;
		cout << i << '\t';
		while (p != NULL)
		{
			cout << p->node << '\t';
			p = p->next;
		}
		cout << endl;
	}
}

int main(void)
{
	int n;       //顶点的个数
	cin >> n;
	Vertex* adjacency_list = NULL;
	build_adjacency_list(adjacency_list, n);		//创建一个邻接表
	cout << "Before reversing:" << endl;
	traverse(adjacency_list, n);					//遍历该邻接表
	Vertex* adverse_adjancency_list = reverse_graph(adjacency_list, n);		//创建一个该邻接表所对应的反向邻接表
	cout << "After reversing:" << endl;
	traverse(adverse_adjancency_list, n);			//遍历该邻接表

	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

amocken

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

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

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

打赏作者

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

抵扣说明:

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

余额充值