c语言,关于邻接表的建立

Python017

c语言,关于邻接表的建立,第1张

AdjList 是自定义类型,是char类型,

第二行 typedef将char类型自定义为 VertexType,即VertexType代表了char型,

VertexType a 就相当于 char a;

同理

倒数第五行 typedef将VertexNode自定义为 AdjList[MaxVertexNum]类型,也就是说现在AdjList就代表了一个 “结构体数组” 类型

AdjList adjlist 相当于 VertexNode adjlist[MaxVertexNum]

这里主要是typedef关键字的使用 希望能帮到你

#include "iostream.h"

const int Max_vertex=5

const int Max_Edge=8

int visited[Max_vertex+1]//访问标志数组

struct ArcNode

{

int adjvex

ArcNode *nextarc //指向下一条弧

}

struct Vnode

{

int v//顶点信息

ArcNode *next

}a[Max_vertex+1]

/* 无向图的建立 */

void creategraph()

{

int i,j,k

ArcNode *s

//初始化

for(i=1i<=Max_vertexi++)

{

a[i].v=i

a[i].next=NULL

}

/*以头插法建立 */

for(k=1k<=Max_Edgek++)

{

cout<<"请输入第"<<k<<"条边:"

cin>>i>>j

if(i>9||i<0||j<0||j>9)

{

cout<<"输入错误!!\n"<<endl

break

}

else{

cout<<endl

s=new ArcNode

s->adjvex=j

s->nextarc=a[i].next

a[i].next=s

s=new ArcNode

s->adjvex=i

s->nextarc=a[j].next

a[j].next=s

}

}

}

void display()

{

ArcNode *p

cout<<"你建立的图为:"<<endl

for(int i=1i<=Max_vertexi++)

{

p=a[i].next

cout<<a[i].v<<"->"

while(p->nextarc!=NULL)

{

cout<<p->adjvex<<"->"

p=p->nextarc

}

cout<<p->adjvex<<endl

}

}

void main()

{

cout<<"/******\t本算法以关插法建立无向图的邻接表为例!\t******/"<<endl

char yn='y'int k

creategraph()

display()

}

在读入顶点信息的时候,将每个点的第一条置为空。如node[x].first_edge = NULL

读入每条边的时候,边的信息应该包括这条边所连接的两个点,即为ilink和jlink。然后执行

edge = malloc...

edge->next_edge = node[ilink].first_edge

node[ilink].first_edge = edge

即,将ilink的第一条边指向刚刚输入的这条边,而该边的下一条边置为原本ilink的第一条边。

重复这一过程,直至读完所有边的信息。