C语言无向图的连接矩阵转为邻接表代码
时间: 2024-10-18 17:05:55 浏览: 44
在C语言中,将无向图的连接矩阵形式转换为邻接表是一种常见的数据结构操作,这有助于提高查找和遍历边的效率。以下是将二维数组表示的连接矩阵转换为邻接表的简单示例。假设我们有一个整数二维数组`graph`表示图,其中`graph[i][j]`为0或1表示是否存在边(i, j)。
```c
#include <stdio.h>
#include <stdlib.h>
// 邻接表结点结构体
typedef struct Node {
int vertex; // 节点值
struct Node* next; // 指向下一个节点的指针
} Node;
// 将连接矩阵转换为邻接表
void matrixToAdjacencyList(int graph[][V], Node** adjList, int V) {
for (int i = 0; i < V; ++i) {
for (int j = 0; j < V; ++j) {
if (graph[i][j]) { // 如果存在边
Node* newNode = (Node*)malloc(sizeof(Node)); // 创建新节点
newNode->vertex = j; // 设置节点值为对应顶点
newNode->next = adjList[i]; // 将新节点添加到邻接列表的链头
adjList[i] = newNode; // 更新邻接表
}
}
}
}
// 示例用途:创建并打印邻接表
void printAdjacencyList(Node** adjList, int V) {
for (int i = 0; i < V; ++i) {
printf("Vertex %d ->", i);
Node* temp = adjList[i];
while (temp != NULL) {
printf("%d ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}
int main() {
int V = sizeof(graph) / sizeof(graph[0]); // 图的顶点数
Node** adjList = (Node**)malloc(V * sizeof(Node*)); // 初始化邻接表
// 假设已经填充了matrix[],这里仅作示例
// matrixToAdjacencyList(graph, adjList, V);
matrixToAdjacencyList(graph, adjList, V); // 转换实际矩阵
printAdjacencyList(adjList, V); // 打印邻接表
return 0;
}
```
阅读全文
相关推荐


















