创建邻接表存储的无向图,并输出图的邻接表。c语言
时间: 2023-11-05 19:17:15 浏览: 182
以下是创建邻接表存储的无向图的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义邻接表结构体
typedef struct node {
int vertex; // 顶点
struct node* next; // 指向下一个节点的指针
} Node;
// 定义无向图结构体
typedef struct graph {
int num_vertices; // 顶点数
Node** adj_list; // 邻接表数组
} Graph;
// 创建节点
Node* create_node(int v) {
Node* node = (Node*)malloc(sizeof(Node));
node->vertex = v;
node->next = NULL;
return node;
}
// 创建无向图
Graph* create_graph(int num_vertices) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->num_vertices = num_vertices;
graph->adj_list = (Node**)malloc(num_vertices * sizeof(Node*));
for (int i = 0; i < num_vertices; i++) {
graph->adj_list[i] = NULL;
}
return graph;
}
// 添加边
void add_edge(Graph* graph, int src, int dest) {
// 添加一条从src到dest的边
Node* node = create_node(dest);
node->next = graph->adj_list[src];
graph->adj_list[src] = node;
// 添加一条从dest到src的边
node = create_node(src);
node->next = graph->adj_list[dest];
graph->adj_list[dest] = node;
}
// 打印邻接表
void print_graph(Graph* graph) {
for (int i = 0; i < graph->num_vertices; i++) {
printf("顶点 %d 的邻接表:", i);
Node* temp = graph->adj_list[i];
while (temp) {
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("NULL\n");
}
}
int main() {
Graph* graph = create_graph(5);
add_edge(graph, 0, 1);
add_edge(graph, 0, 4);
add_edge(graph, 1, 2);
add_edge(graph, 1, 3);
add_edge(graph, 1, 4);
add_edge(graph, 2, 3);
add_edge(graph, 3, 4);
print_graph(graph);
return 0;
}
```
输出结果:
```
顶点 0 的邻接表:4 -> 1 -> NULL
顶点 1 的邻接表:4 -> 3 -> 2 -> 0 -> NULL
顶点 2 的邻接表:3 -> 1 -> NULL
顶点 3 的邻接表:4 -> 2 -> 1 -> NULL
顶点 4 的邻接表:3 -> 1 -> 0 -> NULL
```
阅读全文