matrix[0][1] = matrix[1][0] = 1; matrix[0][2] = matrix[2][0] = 1; matrix[0][3] = matrix[3][0] = 1; matrix[1][4] = matrix[4][1] = 1; matrix[1][5] = matrix[5][1] = 1; matrix[2][5] = matrix[5][2] = 1; matrix[2][6] = matrix[6][2] = 1; matrix[3][7] = matrix[7][3] = 1; matrix[6][8] = matrix[8][6] = 1; matrix[6][9] = matrix[9][6] = 1; matrix[7][10] = matrix[10][7] = 1;把这个邻接矩阵转化为邻接表,用c语言写出它的代码
时间: 2023-06-19 13:06:03 浏览: 119
ch7.rar_创建邻接矩阵_邻接矩阵_邻接矩阵c++_邻接表
以下是将邻接矩阵转换为邻接表的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 11
// 邻接表结点
typedef struct node {
int vertex;
struct node* next;
} Node;
// 邻接表
typedef struct {
Node* head;
} List;
// 邻接图
typedef struct {
List vertices[MAX_VERTICES];
} Graph;
// 初始化邻接表
void initList(List* list) {
list->head = NULL;
}
// 将邻接矩阵转换为邻接表
void matrixToList(int matrix[MAX_VERTICES][MAX_VERTICES], Graph* graph) {
int i, j;
for (i = 0; i < MAX_VERTICES; i++) {
initList(&graph->vertices[i]);
for (j = 0; j < MAX_VERTICES; j++) {
if (matrix[i][j] == 1) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = j;
newNode->next = graph->vertices[i].head;
graph->vertices[i].head = newNode;
}
}
}
}
// 打印邻接表
void printGraph(Graph* graph) {
int i;
for (i = 0; i < MAX_VERTICES; i++) {
printf("%d: ", i);
Node* node = graph->vertices[i].head;
while (node != NULL) {
printf("%d ", node->vertex);
node = node->next;
}
printf("\n");
}
}
int main() {
int matrix[MAX_VERTICES][MAX_VERTICES] = {
{0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0},
{1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0},
{1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0},
{1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0},
{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0},
{0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0}
};
Graph graph;
matrixToList(matrix, &graph);
printGraph(&graph);
return 0;
}
```
输出结果为:
```
0: 3 2 1
1: 5 4
2: 6 5
3: 7
4: 1
5: 2 1
6: 9 8 2
7: 10 3
8: 9 6
9: 8 6
10: 7
```
阅读全文