邻接表

我看了好多博主写的邻接表都不怎么完美,因此整理并且在理解的基础上写了邻接表的代码,我觉得我的代码能够很好的理解(在了解了邻接矩阵的基本原理上)。
在这里插入图片描述
通过这副图,我们能够明白邻接表是链式存储方式 ,我们会发现要完成这种结构的存储必须需要两种不一样的结点 边结点 顶点结点

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cmath>
using namespace std;
//边表结点 
typedef struct EdgeNode
{
	char adjvex;
	char info;
	struct EdgeNode *next; 
}EdgeNode;
//顶点结点 
typedef struct VertexNode
{
	char data;
	struct EdgeNode *firstedge;
}VertexNode,AdjList[25];
typedef struct
{
	AdjList vertices;
	int numVertex,numEdge;
}AdjGraph;
int LocateVex(AdjGraph *g,char vexdata)//需要定位start在g->vertices[i].data中的小标号 
{ 
  int locate;
   //cout<<"g->numvertex="<<g->numVertex<<endl;;
       for(int i=0;i<g->numVertex;i++)
	   {
	   	if((g->vertices[i].data)==vexdata){
	   		   locate=i;
	   		   break;
		   }
	   }	
	   return locate;
}
void Create(AdjGraph *G)
{
     char start,end;
	int locate;	
	EdgeNode *p,*pr;
	cout<<"请输入顶点个数和边数"<<endl;
	cin>>G->numVertex>>G->numEdge;
	cout<<"请输入顶点信息"<<endl; 
	for(int i=0;i<G->numVertex;i++)
	{	
		cin>>G->vertices[i].data;
		G->vertices[i].firstedge=NULL;
	}
	cout<<"输入边(Vi,Vj)中的下标i,j:"<<endl;
	for(int i=0;i<G->numEdge;i++)
	{	
	      if((p=(EdgeNode *)malloc(sizeof(EdgeNode)))==NULL){cout<<"内存分配失败"<<endl; exit(1); }
	      //这种申请内存方式很好 
		  cin>>start>>end; 
		  p->adjvex=end;
		  locate=LocateVex(G,start);//找到start是那个顶点结点 ,才能将边结点插入进去。 
	       p->next=G->vertices[locate].firstedge;//这段代码就是链表在头结点插入结点(希望能够理解) 
	       G->vertices[locate].firstedge=p;
	}
	cout<<"打印邻接表"<<endl; //后面就是链表的遍历 
	for(int i=0;i<G->numVertex;i++)
	{
		
		cout<<G->vertices[i].data; 
		pr=G->vertices[i].firstedge;
		while(pr)
		{
			 cout<<"->"<<pr->adjvex;
			 pr=pr->next;
		}
		cout<<endl;
	}
}
int main()
{
	AdjGraph G;
    Create(&G);
	return 0;
	
} 

这里我说明一下LocateVext函数的作用 它是通过 寻找到start对应的顶点结点 是哪个,寻找到start对应的顶点结点在其后插入边结点。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值