用c语言写一份创建无向图的邻接表程序
时间: 2023-11-21 20:05:57 浏览: 87
数据结构图代码完整版的 C语言实现
3星 · 编辑精心推荐
好的,以下是用C语言创建无向图的邻接表程序的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
// 定义邻接表结点
struct AdjListNode {
int dest;
struct AdjListNode* next;
};
// 定义邻接表
struct AdjList {
struct AdjListNode* head;
};
// 定义图结构
struct Graph {
int V; // 图的顶点数
struct AdjList* array;
};
// 创建邻接表结点
struct AdjListNode* newAdjListNode(int dest) {
struct AdjListNode* newNode = (struct AdjListNode*)malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
// 创建图
struct Graph* createGraph(int V) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V;
graph->array = (struct AdjList*)malloc(V * sizeof(struct AdjList));
int i;
for (i = 0; i < V; ++i) {
graph->array[i].head = NULL;
}
return graph;
}
// 添加邻接表结点
void addEdge(struct Graph* graph, int src, int dest) {
struct AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
newNode = newAdjListNode(src);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}
// 打印邻接表
void printGraph(struct Graph* graph) {
int v;
for (v = 0; v < graph->V; ++v) {
struct AdjListNode* pCrawl = graph->array[v].head;
printf("\n Adjacency list of vertex %d\n head ", v);
while (pCrawl) {
printf("-> %d", pCrawl->dest);
pCrawl = pCrawl->next;
}
printf("\n");
}
}
// 主函数
int main() {
int V = 5;
struct Graph* graph = createGraph(V);
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;
}
```
这是一个简单的示例程序,其中包括创建邻接表结点、创建图、添加邻接表结点、打印邻接表等操作。在主函数中,我们创建了一个5个顶点的无向图,并添加了一些边,最后打印了邻接表。你可以根据自己的需求修改代码,实现更复杂的图操作。
阅读全文