以下是一个较为复杂的 C 语言代码示例,它演示了如何使用链表数据结构实现一个简单的图(Graph)数据结构,并实现图的深度优先搜索(DFS)算法:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int vertex;
struct Node* next;
};
struct Graph {
int numVertices;
struct Node** adjacencyList;
};
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->adjacencyList = malloc(vertices * sizeof(struct Node*));
for (int i = 0; i < vertices; i++) {
graph->adjacencyList[i] = NULL;
}
return graph;
}
void addEdge(struct Graph* graph, int src, int dest) {
struct Node* newNode = createNode(dest);
newNode->next = graph->adjacencyList[src];
graph->adjacencyList[src] = newNode;
newNode = createNode(src);
newNode->next = graph->adjacencyList[dest];
graph->adjacencyList[dest] = newNode;
}
void DFS(struct Graph* graph, int vertex, int* visited) {
visited[vertex] = 1;
printf("%d ", vertex);
struct Node* adjList = graph->adjacencyList[vertex];
while (adjList != NULL) {
int connectedVertex = adjList->vertex;
if (visited[connectedVertex] == 0) {
DFS(graph, connectedVertex, visited);
}
adjList = adjList->next;
}
}
int main() {
int numVertices = 6;
struct Graph* graph = createGraph(numVertices);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);
addEdge(graph, 3, 5);
int visited[numVertices];
for (int i = 0; i < numVertices; i++) {
visited[i] = 0;
}
printf("深度优先搜索结果:");
DFS(graph, 0, visited);
return 0;
}
上述代码实现了一个使用链表数据结构表示的简单无向图(undirected graph)数据结构,并展示了如何实现图的深度优先搜索(DFS)算法。在 main
函数中,我们创建了一个包含 6 个顶点的图,并添加了边连接这些顶点。然后,我们使用深度优先搜索来遍历这个图,并打印出遍历的结果。
请注意,这个例子对于初学者可能具有一定的复杂度,涉及到动态内存分配和链表数据结构的操作。实际编程中,根据需求选择适当的数据结构和算法是非常重要的。
标签:Node,struct,示例,int,graph,代码,newNode,adjacencyList,语言 From: https://blog.51cto.com/u_15964895/7711271