有向图的邻接表转逆邻接表的算法

#include <iostream>
using namespace std;
typedef struct ArcNode{
	int adjvex;
	int weight;
	ArcNode *next;
}ArcNode;

typedef struct VertexNode{
	int vertex;
	ArcNode *firstarc;
}VertexNode,AdjList[100];

typedef struct GraphAdjList{
	AdjList adjlist;
	int vexnum;
	int arcnum;
}GraphAdjList;


void createGraphAdjList(GraphAdjList &G){
	cin >> G.vexnum >> G.arcnum;
	for(int i = 0; i < G.vexnum; i++){
		cin >> G.adjlist[i].vertex;
		G.adjlist[i].firstarc = NULL;
	}
	
	ArcNode *p;
	for(int k = 0; k < G.arcnum; k++){
		int i,j,w;
		cin >> i >> j >> w;
		p = new ArcNode;
		p->adjvex = j;
		p->weight = w;
		p->next = G.adjlist[i].firstarc; //头插法 
		G.adjlist[i].firstarc = p;
	}
	
}

void transOutToIn(GraphAdjList gOut,GraphAdjList &gIn){
	
	gIn.vexnum =  gOut.vexnum; //初始化逆邻接表顶点数目   
	gIn.arcnum =  gOut.arcnum; //初始化逆邻接表边数目  
	
	for(int i = 0; i < gOut.vexnum; i++){
		gIn.adjlist[i].vertex = gOut.adjlist[i].vertex;//构造逆邻接表顶点向量 
		gIn.adjlist[i].firstarc = NULL;
	}
	
	for(int i = 0; i < gOut.vexnum; i++){
		ArcNode *p,*s;
		int j;
		
		p = gOut.adjlist[i].firstarc;//取出邻接表中第i个顶点的指向邻接表的指针   
		
		while(p){  //遍历邻接表中第i个顶点所有邻接边 
			j = p->adjvex;  
			s = new ArcNode;
			s->adjvex = i;//将 i 挂到 gIn.adjlist[j]上
			s->weight = p->weight;
			s->next = gIn.adjlist[j].firstarc; //将 i 挂到 j上 
			gIn.adjlist[j].firstarc = s;
			p = p->next;
		}
	}
	

}

void printfGraphAdjList(GraphAdjList G){
		for(int i = 0; i < G.vexnum; i++){
			ArcNode *p = G.adjlist[i].firstarc;
			cout << G.adjlist[i].vertex << "\t";
			while(p){
				cout << p->adjvex << " " << p->weight << "\t";
				p = p->next;
			}
		
			cout << endl;
		}
		
		
}

int main(){
	
	GraphAdjList gOut,gIn;//gOut邻接表  gIn逆邻接表 
	createGraphAdjList(gOut);//构造邻接表 
	printfGraphAdjList(gOut);//打印邻接表 
	transOutToIn(gOut,gIn); //由邻接表转化为逆邻接表  
	printfGraphAdjList(gIn);//打印逆邻接表 
	return 0;
	 
}

 

  • 11
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值