C语言 图的基本操作:2.基于邻接表建立图 《实验二:基于邻接表建立图》 (1) 要求:补全代码 (2) 测试用例: 输入 输出 4 3↵ abcd↵ a,b b,c b,d 用邻接表来创建图↵ 请输入图的顶点个数和弧数↵ 请用一行输入图的各个顶点,不用逗号隔开↵ 请用一行输入图中所有两顶点之间的弧,例如,a,b b,c b,d↵ 打印出用邻接表创建的无向图↵ a----> c b ↵ b----> d a ↵ c----> a ↵ d--
时间: 2024-03-02 20:54:21 浏览: 76
以下是基于邻接表建立图的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20
typedef struct ArcNode {
int adjvex;
struct ArcNode *next;
}ArcNode;
typedef struct VNode {
char data;
ArcNode *firstarc;
}VNode, AdjList[MAX_VERTEX_NUM];
typedef struct {
AdjList vertices;
int vexnum, arcnum;
}ALGraph;
void CreateGraph(ALGraph *G) {
printf("请输入图的顶点个数和弧数\n");
scanf("%d%d", &G->vexnum, &G->arcnum);
getchar(); // 消耗回车符
printf("请用一行输入图的各个顶点,不用逗号隔开\n");
for (int i = 0; i < G->vexnum; i++) {
scanf("%c", &G->vertices[i].data);
G->vertices[i].firstarc = NULL;
}
getchar(); // 消耗回车符
printf("请用一行输入图中所有两顶点之间的弧,例如,a,b b,c b,d\n");
for (int i = 0; i < G->arcnum; i++) {
char v1, v2;
scanf("%c%c", &v1, &v2);
getchar(); // 消耗回车符
int index1, index2;
for (int j = 0; j < G->vexnum; j++) {
if (G->vertices[j].data == v1) index1 = j;
if (G->vertices[j].data == v2) index2 = j;
}
ArcNode *arc1 = (ArcNode *)malloc(sizeof(ArcNode));
arc1->adjvex = index2;
arc1->next = G->vertices[index1].firstarc;
G->vertices[index1].firstarc = arc1;
ArcNode *arc2 = (ArcNode *)malloc(sizeof(ArcNode));
arc2->adjvex = index1;
arc2->next = G->vertices[index2].firstarc;
G->vertices[index2].firstarc = arc2;
}
}
void PrintGraph(ALGraph G) {
for (int i = 0; i < G.vexnum; i++) {
printf("%c---->", G.vertices[i].data);
ArcNode *arc = G.vertices[i].firstarc;
while (arc != NULL) {
printf(" %c ", G.vertices[arc->adjvex].data);
arc = arc->next;
}
printf("\n");
}
}
int main() {
ALGraph G;
CreateGraph(&G);
printf("打印出用邻接表创建的无向图\n");
PrintGraph(G);
return 0;
}
```
测试用例:
输入:
```
4 3
abcd
a,b b,c b,d
```
输出:
```
打印出用邻接表创建的无向图
a----> c b
b----> d a
c----> a
d----> b
```
阅读全文