请用C语言编程实现图的邻接矩阵和邻接表两种存储结构
时间: 2024-06-09 19:06:42 浏览: 188
数据结构学习--图的邻接矩阵和邻接表存储
邻接矩阵:
```c
#include <stdio.h>
#define MAX_VERTEX_NUM 100 // 最大顶点数
typedef struct Graph {
int vertexNum; // 顶点数
int edgeNum; // 边数
int matrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; // 邻接矩阵
} Graph;
void initGraph(Graph *graph, int vertexNum) {
graph->vertexNum = vertexNum;
graph->edgeNum = 0;
for (int i = 0; i < vertexNum; i++) {
for (int j = 0; j < vertexNum; j++) {
graph->matrix[i][j] = 0;
}
}
}
void addEdge(Graph *graph, int from, int to) {
graph->matrix[from][to] = 1;
graph->edgeNum++;
}
void printGraph(Graph *graph) {
printf("vertex num: %d, edge num: %d\n", graph->vertexNum, graph->edgeNum);
for (int i = 0; i < graph->vertexNum; i++) {
for (int j = 0; j < graph->vertexNum; j++) {
printf("%d ", graph->matrix[i][j]);
}
printf("\n");
}
}
int main() {
Graph graph;
initGraph(&graph, 5);
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;
}
```
邻接表:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 100 // 最大顶点数
typedef struct EdgeNode {
int to;
struct EdgeNode *next;
} EdgeNode;
typedef struct VertexNode {
int data;
EdgeNode *firstEdge;
} VertexNode;
typedef struct Graph {
VertexNode vertices[MAX_VERTEX_NUM]; // 顶点数组
int vertexNum; // 顶点数
int edgeNum; // 边数
} Graph;
void initGraph(Graph *graph, int vertexNum) {
graph->vertexNum = vertexNum;
graph->edgeNum = 0;
for (int i = 0; i < vertexNum; i++) {
graph->vertices[i].data = i;
graph->vertices[i].firstEdge = NULL;
}
}
void addEdge(Graph *graph, int from, int to) {
EdgeNode *edgeNode = (EdgeNode*)malloc(sizeof(EdgeNode));
edgeNode->to = to;
edgeNode->next = NULL;
if (graph->vertices[from].firstEdge == NULL) {
graph->vertices[from].firstEdge = edgeNode;
} else {
EdgeNode *p = graph->vertices[from].firstEdge;
while (p->next != NULL) {
p = p->next;
}
p->next = edgeNode;
}
graph->edgeNum++;
}
void printGraph(Graph *graph) {
printf("vertex num: %d, edge num: %d\n", graph->vertexNum, graph->edgeNum);
for (int i = 0; i < graph->vertexNum; i++) {
printf("%d: ", graph->vertices[i].data);
EdgeNode *p = graph->vertices[i].firstEdge;
while (p != NULL) {
printf("%d ", p->to);
p = p->next;
}
printf("\n");
}
}
int main() {
Graph graph;
initGraph(&graph, 5);
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;
}
```
阅读全文