用c语言写一个无向图的邻接表
时间: 2023-11-14 14:06:59 浏览: 95
无向图的邻接表表示
4星 · 用户满意度95%
下面是用C语言实现无向图的邻接表:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义一个邻接表节点
struct AdjListNode {
int dest;
struct AdjListNode* next;
};
// 定义邻接表头结点
struct AdjList {
struct AdjListNode* head;
};
// 定义图结构
struct Graph {
int V; // 顶点数量
struct AdjList* array;
};
// 创建一个邻接表节点
struct AdjListNode* newAdjListNode(int dest) {
struct AdjListNode* newNode = (struct AdjListNode*)malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
// 创建图
struct Graph* createGraph(int V) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V;
graph->array = (struct AdjList*)malloc(V * sizeof(struct AdjList));
for (int i = 0; i < V; ++i) {
graph->array[i].head = NULL;
}
return graph;
}
// 添加边到无向图中
void addEdge(struct Graph* graph, int src, int dest) {
// 添加一条边从源到目标
struct AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
// 添加一条边从目标到源,因为是无向图
newNode = newAdjListNode(src);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}
// 打印图的邻接表表示
void printGraph(struct Graph* graph) {
for (int i = 0; i < graph->V; ++i) {
struct AdjListNode* head = graph->array[i].head;
printf("\n顶点 %d 的邻接表为\nhead ", i);
while (head) {
printf("-> %d", head->dest);
head = head->next;
}
printf("\n");
}
}
int main() {
int V = 5;
struct Graph* graph = createGraph(V);
addEdge(graph, 0, 1);
addEdge(graph, 0, 4);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);
printGraph(graph);
return 0;
}
```
输出结果为:
```
顶点 0 的邻接表为
head -> 4 -> 1
顶点 1 的邻接表为
head -> 4 -> 3 -> 2 -> 0
顶点 2 的邻接表为
head -> 3 -> 1
顶点 3 的邻接表为
head -> 4 -> 2 -> 1
顶点 4 的邻接表为
head -> 3 -> 1 -> 0
```
阅读全文