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