C语言带权无向图的邻接表创建和输出
时间: 2024-03-17 07:46:44 浏览: 11
邻接表是一种表示图的常见数据结构,用于存储图中节点之间的连接关系。以下是C语言中创建和输出带权无向图邻接表的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义邻接表节点
struct AdjListNode {
int dest;
int weight;
struct AdjListNode* next;
};
// 定义邻接表头结点
struct AdjList {
struct AdjListNode* head;
};
// 定义图
struct Graph {
int V;
struct AdjList* array;
};
// 创建新节点
struct AdjListNode* newAdjListNode(int dest, int weight) {
struct AdjListNode* newNode = (struct AdjListNode*)malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->weight = weight;
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, int weight) {
struct AdjListNode* newNode = newAdjListNode(dest, weight);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
newNode = newAdjListNode(src, weight);
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* node = graph->array[i].head;
printf("\n邻接表节点 %d 的项为:\n", i);
while (node) {
printf("%d(权重为 %d) -> ", node->dest, node->weight);
node = node->next;
}
printf("NULL\n");
}
}
int main() {
int V = 4;
struct Graph* graph = createGraph(V);
addEdge(graph, 0, 1, 10);
addEdge(graph, 0, 2, 6);
addEdge(graph, 0, 3, 5);
addEdge(graph, 1, 3, 15);
addEdge(graph, 2, 3, 4);
printGraph(graph);
return 0;
}
```
输出结果:
```
邻接表节点 0 的项为:
1(权重为 10) -> 3(权重为 5) -> 2(权重为 6) -> NULL
邻接表节点 1 的项为:
0(权重为 10) -> 3(权重为 15) -> NULL
邻接表节点 2 的项为:
0(权重为 6) -> 3(权重为 4) -> NULL
邻接表节点 3 的项为:
0(权重为 5) -> 1(权重为 15) -> 2(权重为 4) -> NULL
```