c语言 实现图的邻接表的存储 编写程序,输入顶点的个数、边的个数、每个顶点的值、每 一条边及其权值,建立带权无向图 G 的邻接表,并输出
时间: 2024-02-15 19:04:25 浏览: 79
好的,下面是 C 语言实现图的邻接表存储的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20
typedef struct EdgeNode {
int adjvex;
int weight;
struct EdgeNode *next;
} EdgeNode;
typedef struct VertexNode {
int data;
EdgeNode *firstEdge;
} VertexNode;
typedef struct {
VertexNode vertex[MAX_VERTEX_NUM];
int vertexNum, edgeNum;
} Graph;
void createGraph(Graph *graph) {
printf("请输入图的顶点数和边数:\n");
scanf("%d %d", &(graph->vertexNum), &(graph->edgeNum));
printf("请输入图的顶点:\n");
for (int i = 0; i < graph->vertexNum; i++) {
scanf("%d", &(graph->vertex[i].data));
graph->vertex[i].firstEdge = NULL;
}
printf("请输入图的边的信息(格式:起点 终点 权值):\n");
for (int k = 0; k < graph->edgeNum; k++) {
int i, j, w;
scanf("%d %d %d", &i, &j, &w);
EdgeNode *e1 = (EdgeNode *) malloc(sizeof(EdgeNode));
e1->adjvex = j;
e1->weight = w;
e1->next = graph->vertex[i].firstEdge;
graph->vertex[i].firstEdge = e1;
EdgeNode *e2 = (EdgeNode *) malloc(sizeof(EdgeNode));
e2->adjvex = i;
e2->weight = w;
e2->next = graph->vertex[j].firstEdge;
graph->vertex[j].firstEdge = e2;
}
}
void printGraph(Graph *graph) {
printf("图的邻接表为:\n");
for (int i = 0; i < graph->vertexNum; i++) {
printf("%d -> ", graph->vertex[i].data);
EdgeNode *p = graph->vertex[i].firstEdge;
while (p) {
printf("%d(%d) ", graph->vertex[p->adjvex].data, p->weight);
p = p->next;
}
printf("\n");
}
}
int main() {
Graph graph;
createGraph(&graph);
printGraph(&graph);
return 0;
}
```
这个程序实现了创建一个带权无向图的邻接表,并打印出来。其中,`Graph` 结构体表示一个图,包含 `vertex` 数组表示顶点,`vertexNum` 表示顶点数,`edgeNum` 表示边数。在 `createGraph` 函数中,先输入顶点数和边数,然后分别输入顶点和边的信息,最后根据边的信息构建邻接表。在 `printGraph` 函数中,先打印每个顶点,然后打印每个顶点的边,包括边的终点和权值。
阅读全文