用c语言以邻接表的形式创建一个无向图:分析过程
时间: 2024-05-09 15:16:17 浏览: 103
创建一个无向图,需要定义图的节点和边。邻接表是一种常见的图存储方式,其基本思想是将每个节点的邻居节点存储在一个链表中。
1. 定义节点结构体
首先,我们需要定义节点结构体。每个节点包含一个标识符和指向邻居节点的指针。
```
typedef struct node {
int value; // 节点的标识符
struct node *next; // 指向下一个邻居节点的指针
} Node;
```
2. 定义图结构体
然后,我们定义图结构体。图结构体包含一个节点数组和节点数量。
```
typedef struct graph {
Node **nodes; // 节点数组,每个节点指向一个邻居链表
int numNodes; // 节点数量
} Graph;
```
3. 初始化图
接着,我们初始化图。我们需要为节点数组分配内存,并将每个节点的邻居链表初始化为空。
```
Graph *createGraph(int numNodes) {
Graph *graph = (Graph *)malloc(sizeof(Graph));
graph->numNodes = numNodes;
graph->nodes = (Node **)malloc(numNodes * sizeof(Node *));
for (int i = 0; i < numNodes; i++) {
graph->nodes[i] = NULL;
}
return graph;
}
```
4. 添加边
现在,我们可以添加边了。对于无向图,每条边需要在两个节点之间建立连接。我们可以通过向节点的邻居链表中添加节点来实现连接。
```
void addEdge(Graph *graph, int src, int dest) {
// 添加从 src 到 dest 的边
Node *node = (Node *)malloc(sizeof(Node));
node->value = dest;
node->next = graph->nodes[src];
graph->nodes[src] = node;
// 添加从 dest 到 src 的边
node = (Node *)malloc(sizeof(Node));
node->value = src;
node->next = graph->nodes[dest];
graph->nodes[dest] = node;
}
```
5. 打印图
最后,我们可以打印图,以验证我们的实现是否正确。
```
void printGraph(Graph *graph) {
for (int i = 0; i < graph->numNodes; i++) {
printf("Node %d: ", i);
Node *node = graph->nodes[i];
while (node) {
printf("%d ", node->value);
node = node->next;
}
printf("\n");
}
}
```
完整代码如下:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value;
struct node *next;
} Node;
typedef struct graph {
Node **nodes;
int numNodes;
} Graph;
Graph *createGraph(int numNodes) {
Graph *graph = (Graph *)malloc(sizeof(Graph));
graph->numNodes = numNodes;
graph->nodes = (Node **)malloc(numNodes * sizeof(Node *));
for (int i = 0; i < numNodes; i++) {
graph->nodes[i] = NULL;
}
return graph;
}
void addEdge(Graph *graph, int src, int dest) {
Node *node = (Node *)malloc(sizeof(Node));
node->value = dest;
node->next = graph->nodes[src];
graph->nodes[src] = node;
node = (Node *)malloc(sizeof(Node));
node->value = src;
node->next = graph->nodes[dest];
graph->nodes[dest] = node;
}
void printGraph(Graph *graph) {
for (int i = 0; i < graph->numNodes; i++) {
printf("Node %d: ", i);
Node *node = graph->nodes[i];
while (node) {
printf("%d ", node->value);
node = node->next;
}
printf("\n");
}
}
int main() {
int numNodes = 5;
Graph *graph = createGraph(numNodes);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
addEdge(graph, 2, 3);
addEdge(graph, 2, 4);
printGraph(graph);
return 0;
}
```
阅读全文