您的位置:首页 > 编程语言 > C语言/C++

C语言邻接表表示法创建无向图并输出

2020-07-21 04:12 2521 查看

C语言邻接表表示法创建无向图并输出

邻接表是图的一种链式存储结构,对图的每个顶点建立一个单链表,单链表第一个结点存放顶点信息,其余存放有关边信息。
邻接表由表头结点表和边表组成。

  • 邻接表存储结构
#include <stdio.h>
#include <stdlib.h>
//- - - - -图的邻接表存储表示- ----
#define MAX 100   //最大顶点数
typedef struct ArcNode   //边结点
{
int adjvex;  //边顶点位置
struct ArcNode * nextarc;
}ArcNode;
typedef struct VNode  //顶点
{
char data;
ArcNode * firstarc;
}VNode;
typedef struct
{
VNode AdjList[ MAX ];
int vexnum,arcnum;  //图的当前顶点数和边数
}ALGraph;
  • 创建无向图
算法步骤:
1、输入总顶点数和总边数
2、依次输入顶点信息存入顶点表中,并使表头结点的指针域初始化为NULL
3、创建邻接表。依次输入每条边依附的两个顶点,确定两个顶点的序号,将此边结点插入对应的边链表头部。
int LocateVex(ALGraph G,char v) //根据v点信息,找到相应坐标
{
for(int i=0;i<G.vexnum;++i)
{
if(G.AdjList[i].data==v)
return i;
}
return -1;
}
int CreateUDG(ALGraph * G)
{
char v1,v2;
int i,j;
ArcNode *p1,*p2;
printf("输入顶点数和边数");
scanf("%d%d",&G->vexnum,&G->arcnum);

printf("输入顶点数据:");
for(int c=0;c<G->vexnum;++c)
{
scanf(" %c", &G->AdjList[c].data);  //%c前面空格就是用来屏蔽空白符的
G->AdjList[c].firstarc=NULL;       //在用"%c"输入时,空格和“转义字符”均作为有效字符
}
printf("输入边的两个顶点\n");
for(int k=0;k<G->arcnum;++k)
{
scanf(" %c %c",&v1,&v2);
i=LocateVex(*G,v1);  //确定顶点位置
j=LocateVex(*G,v2);

p1=(ArcNode*)malloc(sizeof(ArcNode));  //p1插入边表头部
p1->adjvex=i;
p1->nextarc=G->AdjList[j].firstarc;  //链表前插法
G->AdjList[j].firstarc=p1;

p2=(ArcNode*)malloc(sizeof(ArcNode));
p2->adjvex=j;
p2->nextarc=G->AdjList[i].firstarc;
G->AdjList[i].firstarc=p2;
}
return 0;
}
  • 输出图的邻接表
void output_AL(ALGraph G)  //输出
{
for(int i=0;i<G.vexnum;i++)
{
printf("顶点%c",G.AdjList[i].data);
ArcNode * p=G.AdjList[i].firstarc;
while(p!=NULL)
{
printf("->%d",p->adjvex); //输出下标
//printf("->%c",G.AdjList[p->adjvex].data);  //输出顶点元素
p=p->nextarc;
}
printf("\n");
}
}
  • 主函数
int main()
{
ALGraph G;
CreateUDG(&G);
output_AL(G);
return 0;
}
  • 运行结果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐