0
点赞
收藏
分享

微信扫一扫

邻接表(链表模拟)

圣杰 2022-03-30 阅读 47

= =网上有很多大佬写的数组模拟的邻接表,还不是特别能理解,尤其是结构体中间那一块的next明明是指向前一个的却写成next。这里记录一下我用链表实现的,清楚简单,至少比数组模拟容易理解

#include <iostream>
using namespace std;

struct EdgeNode{
	//如果有需要自行建立内容,如int weight(权值)
	int toVex;
	EdgeNode *next;
};

struct VexNode{
	//同上,如int data
	EdgeNode *firstEdge=NULL;
	EdgeNode *lastEdge=NULL;
}VexList[100];

void add(int u,int v){//建图
	EdgeNode *edge = new EdgeNode;
	edge->toVex=v;
	edge->next=NULL;
	if(VexList[u].firstEdge==NULL){
		VexList[u].lastEdge=VexList[u].firstEdge=edge;
	}else{
		VexList[u].lastEdge->next=edge;//用尾指针插入新内容
		VexList[u].lastEdge=VexList[u].lastEdge->next;
	}	
}

int main(){
	int u,v;
	while(cin>>u>>v){
		if(u==0&&v==0)break;
		add(u,v);
	}
	for(EdgeNode *travel=VexList[1].firstEdge;travel!=NULL;travel=travel->next){//遍历
		cout<<"1->"<<travel->toVex<<endl;
	}
	return 0;
}

 在此图的基础上多了一个lastEdge指针,方便插入,插入的时候就不用遍历了,写起来还方便点,虽然相当于没变化(雾

举报

相关推荐

0 条评论