c语言建立无向图
时间: 2023-07-09 07:11:29 浏览: 123
无向图的建立和遍历(C++)
5星 · 资源好评率100%
要建立一个无向图,可以使用邻接表来进行表示。邻接表是一种数据结构,用于表示图中每个节点所有相邻节点的集合。
下面是一个示例代码,可以创建一个无向图:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int vertex;
struct Node* next;
} Node;
typedef struct Graph {
int num_vertices;
Node** adj_list;
} Graph;
Node* create_node(int v) {
Node* node = (Node*)malloc(sizeof(Node));
node->vertex = v;
node->next = NULL;
return node;
}
Graph* create_graph(int num_vertices) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->num_vertices = num_vertices;
graph->adj_list = (Node**)malloc(num_vertices * sizeof(Node*));
for (int i = 0; i < num_vertices; ++i) {
graph->adj_list[i] = NULL;
}
return graph;
}
void add_edge(Graph* graph, int src, int dest) {
Node* node = create_node(dest);
node->next = graph->adj_list[src];
graph->adj_list[src] = node;
node = create_node(src);
node->next = graph->adj_list[dest];
graph->adj_list[dest] = node;
}
void print_graph(Graph* graph) {
for (int i = 0; i < graph->num_vertices; ++i) {
Node* tmp = graph->adj_list[i];
printf("\nAdjacency list of vertex %d\n head ", i);
while (tmp) {
printf("-> %d", tmp->vertex);
tmp = tmp->next;
}
printf("\n");
}
}
int main() {
Graph* graph = create_graph(4);
add_edge(graph, 0, 1);
add_edge(graph, 0, 2);
add_edge(graph, 1, 2);
add_edge(graph, 2, 3);
print_graph(graph);
return 0;
}
```
上面的代码创建了一个有四个节点的无向图,并在它们之间添加了几条边。您可以根据需要修改该代码以创建更大或更小的无向图。
阅读全文