用c语言写个图的邻接表
时间: 2023-09-28 19:10:58 浏览: 59
用c语言写的图的邻接表操作集合
下面是用C语言实现图的邻接表:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义邻接表节点结构体
typedef struct AdjListNode {
int dest;
struct AdjListNode* next;
} AdjListNode;
// 定义邻接表头结构体
typedef struct AdjList {
AdjListNode* head;
} AdjList;
// 定义图结构体
typedef struct Graph {
int V;
AdjList* array;
} Graph;
// 创建邻接表节点
AdjListNode* newAdjListNode(int dest) {
AdjListNode* newNode = (AdjListNode*)malloc(sizeof(AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
// 创建图
Graph* createGraph(int V) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->V = V;
graph->array = (AdjList*)malloc(V * sizeof(AdjList));
for (int i = 0; i < V; ++i) {
graph->array[i].head = NULL;
}
return graph;
}
// 添加边
void addEdge(Graph* graph, int src, int dest) {
// 添加从源节点到目标节点的边
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(Graph* graph) {
for (int i = 0; i < graph->V; ++i) {
AdjListNode* ptr = graph->array[i].head;
printf("节点 %d 的邻接表为:", i);
while (ptr) {
printf(" -> %d", ptr->dest);
ptr = ptr->next;
}
printf("\n");
}
}
int main() {
int V = 5;
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 的邻接表为: -> 4 -> 1
节点 1 的邻接表为: -> 4 -> 3 -> 2 -> 0
节点 2 的邻接表为: -> 3 -> 1
节点 3 的邻接表为: -> 4 -> 2 -> 1
节点 4 的邻接表为: -> 3 -> 1 -> 0
```
其中,每个节点的邻接表记录了与该节点相连的所有节点。
阅读全文