使用C语言请编程实现图的邻接矩阵和邻接表两种存储结构
时间: 2024-05-07 11:21:13 浏览: 132
邻接矩阵存储结构:
```c
#include<stdio.h>
#include<stdlib.h>
#define MAX_VERTEX_NUM 20
typedef struct {
int vertex[MAX_VERTEX_NUM];
int edge[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int vexnum, edgenum;
}Graph;
void createGraph(Graph *G);
void printGraph(Graph G);
int main() {
Graph G;
createGraph(&G);
printGraph(G);
return 0;
}
void createGraph(Graph *G) {
int i, j, k, w;
printf("请输入顶点数和边数(用空格隔开):");
scanf("%d%d", &G->vexnum, &G->edgenum);
printf("请输入顶点信息:");
for (i = 0; i < G->vexnum; i++)
scanf("%d", &G->vertex[i]);
for (i = 0; i < G->vexnum; i++) {
for (j = 0; j < G->vexnum; j++) {
G->edge[i][j] = 0;
}
}
printf("请输入边的信息:\n");
for (k = 0; k < G->edgenum; k++) {
printf("第%d条边(i,j,w):", k + 1);
scanf("%d%d%d", &i, &j, &w);
G->edge[i - 1][j - 1] = w;
G->edge[j - 1][i - 1] = w;
}
}
void printGraph(Graph G) {
int i, j;
printf("\n邻接矩阵:\n");
for (i = 0; i < G.vexnum; i++) {
for (j = 0; j < G.vexnum; j++) {
printf("%d ", G.edge[i][j]);
}
printf("\n");
}
}
```
邻接表存储结构:
```c
#include<stdio.h>
#include<stdlib.h>
#define MAX_VERTEX_NUM 20
typedef struct ArcNode {
int adjvex;
int weight;
struct ArcNode *next;
}ArcNode;
typedef struct {
int data;
ArcNode *firstarc;
}VNode;
typedef struct {
VNode vertex[MAX_VERTEX_NUM];
int vexnum, edgenum;
}Graph;
void createGraph(Graph *G);
void printGraph(Graph G);
int main() {
Graph G;
createGraph(&G);
printGraph(G);
return 0;
}
void createGraph(Graph *G) {
int i, j, k, w;
ArcNode *p;
printf("请输入顶点数和边数(用空格隔开):");
scanf("%d%d", &G->vexnum, &G->edgenum);
printf("请输入顶点信息:");
for (i = 0; i < G->vexnum; i++) {
scanf("%d", &G->vertex[i].data);
G->vertex[i].firstarc = NULL;
}
printf("请输入边的信息:\n");
for (k = 0; k < G->edgenum; k++) {
printf("第%d条边(i,j,w):", k + 1);
scanf("%d%d%d", &i, &j, &w);
p = (ArcNode*)malloc(sizeof(ArcNode));
p->adjvex = j - 1;
p->weight = w;
p->next = G->vertex[i - 1].firstarc;
G->vertex[i - 1].firstarc = p;
p = (ArcNode*)malloc(sizeof(ArcNode));
p->adjvex = i - 1;
p->weight = w;
p->next = G->vertex[j - 1].firstarc;
G->vertex[j - 1].firstarc = p;
}
}
void printGraph(Graph G) {
int i;
ArcNode *p;
printf("\n邻接表:\n");
for (i = 0; i < G.vexnum; i++) {
printf("%d:", G.vertex[i].data);
p = G.vertex[i].firstarc;
while (p) {
printf("-> %d(%d)", G.vertex[p->adjvex].data, p->weight);
p = p->next;
}
printf("\n");
}
}
```
阅读全文