邻接表创建无向图c语言代码
时间: 2023-10-15 21:04:36 浏览: 40
以下是邻接表创建无向图的 C 语言代码:
```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*));
int i;
for (i = 0; i < vertices; i++)
graph->adjLists[i] = NULL;
return graph;
}
void addEdge(struct Graph* graph, int src, int dest) {
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
void displayGraph(struct Graph* graph) {
int i;
for (i = 0; i < graph->numVertices; i++) {
struct node* temp = graph->adjLists[i];
printf("\n Adjacency list of vertex %d\n ", i);
while (temp) {
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("NULL\n");
}
}
int main() {
struct Graph* graph = createGraph(4);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 3);
displayGraph(graph);
return 0;
}
```
这个代码创建了一个包含 4 个顶点的无向图,并且使用邻接表来表示它。`createNode` 函数创建一个新节点,`createGraph` 函数创建一个新图,`addEdge` 函数向图中添加一条边,`displayGraph` 函数打印图的邻接表表示形式。这个程序的输出如下:
```
Adjacency list of vertex 0
2 -> 1 -> NULL
Adjacency list of vertex 1
2 -> 0 -> NULL
Adjacency list of vertex 2
3 -> 1 -> 0 -> NULL
Adjacency list of vertex 3
2 -> NULL
```
这个输出表示了每个顶点的邻接列表,其中每个列表包含与该顶点相邻的所有顶点。例如,顶点 0 的邻接列表包含顶点 1 和 2,而顶点 2 的邻接列表包含顶点 1、0 和 3。这个程序可以根据需要进行修改以创建任何大小和形状的无向图。