用邻接表的方式创建一个图
时间: 2023-11-11 20:18:29 浏览: 44
好的,我可以为您提供使用邻接表的方式创建图的示例代码。
邻接表是一种用于表示图的数据结构,它将图中的每个节点表示为一个链表,链表中存储与该节点相邻的其他节点。与邻接矩阵相比,邻接表可以更好地处理稀疏图,并且可以更快地查找给定节点的相邻节点。
以下是一个使用邻接表创建无向图的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义邻接表中的节点结构
struct Node {
int vertex;
struct Node* next;
};
// 定义图结构
struct Graph {
int numVertices;
struct Node** adjLists;
};
// 创建节点
struct Node* createNode(int v) {
struct Node* newNode = malloc(sizeof(struct Node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// 创建图
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
// 创建邻接表
graph->adjLists = malloc(vertices * sizeof(struct Node*));
for (int i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
}
return graph;
}
// 添加边
void addEdge(struct Graph* graph, int src, int dest) {
// 添加从src到dest的边
struct Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// 添加从dest到src的边
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
// 打印邻接表
void printGraph(struct Graph* graph) {
for (int i = 0; i < graph->numVertices; i++) {
struct Node* temp = graph->adjLists[i];
printf("Vertex %d: ", i);
while (temp) {
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("NULL\n");
}
}
int main() {
struct Graph* graph = createGraph(5);
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;
}
```
在上面的代码中,我们首先定义了一个节点结构体Node,其中vertex表示节点的值,next表示链表中的下一个节点。然后,我们定义了一个图结构体Graph,其中numVertices表示图中节点的总数,adjLists是一个指针数组,每个指针指向一个邻接表。
在createNode函数中,我们创建一个新节点,并将vertex设置为v,将next设置为NULL。然后,在createGraph函数中,我们创建一个新图,并将numVertices设置为给定的vertices值。然后,我们为每个节点创建一个空邻接表。
在addEdge函数中,我们添加从src到dest的边和从dest到src的边。具体来说,我们首先创建一个指向dest的新节点,并将其添加到src节点的邻接表中。然后,我们创建一个指向src的新节点,并将其添加到dest节点的邻接表中。
在printGraph函数中,我们遍历整个邻接表,并打印出每个节点的值以及它的邻居节点。最后,在main函数中,我们创建一个新图,并添加7条边,然后调用printGraph函数来打印出整个图的邻接表表示。
当您运行这段代码时,您将看到以下输出:
```
Vertex 0: 4 -> 1 -> NULL
Vertex 1: 4 -> 3 -> 2 -> 0 -> NULL
Vertex 2: 3 -> 1 -> NULL
Vertex 3: 4 -> 2 -> 1 -> NULL
Vertex 4: 3 -> 1 -> 0 -> NULL
```
这里的每一行代表一个节点,它的邻居节点由箭头表示。例如,第一行表示节点0有两个邻居节点,分别是4和1。