邻接表创建无向图c语言代码
时间: 2023-10-15 09:04:31 浏览: 107
以下是使用邻接表创建无向图的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Graph {
int numVertices;
struct Node** adjLists;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
struct Graph* createGraph(int vertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = (struct Node**)malloc(vertices * sizeof(struct Node*));
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
}
return graph;
}
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// Add edge from dest to src
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
void printGraph(struct Graph* graph) {
int v;
for (v = 0; v < graph->numVertices; v++) {
struct Node* temp = graph->adjLists[v];
printf("\n Adjacency list of vertex %d\n head ", v);
while (temp) {
printf("-> %d", temp->data);
temp = temp->next;
}
printf("\n");
}
}
int main() {
struct Graph* graph = createGraph(4);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 3);
printGraph(graph);
return 0;
}
```
在上面的代码中,我们首先定义了一个 `Node` 结构体来表示节点,其中包括节点的数据和指向下一个节点的指针。然后,我们定义了一个 `Graph` 结构体来表示无向图,其中包括节点数量和一个指向邻接表的指针数组。`createNode` 函数用于创建新节点,`createGraph` 函数用于创建无向图并初始化邻接表,`addEdge` 函数用于添加边,`printGraph` 函数用于打印邻接表。在 `main` 函数中,我们创建一个包含 4 个节点的无向图,并添加 4 条边。最后,我们打印出邻接表来验证图是否正确创建。
阅读全文