自定义图的邻接矩阵和邻接表两种存储结构。以下两项任选其一: (1)创建图的邻接矩阵,设计算法自动生成邻接表,或: (2)创建图的邻接表,设计算法自动生成邻接矩阵。 要求能够打印图的邻接矩阵和邻接表,进行验证。 用C语言实现
时间: 2024-05-12 18:14:26 浏览: 82
图的邻接表存储C语言实现
以下是使用邻接矩阵生成邻接表的算法实现,包括打印邻接矩阵和邻接表的功能。
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 100
typedef struct {
int vertex[MAX_VERTEX_NUM];
int edge[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int vertex_num, edge_num;
} Graph;
typedef struct {
int vertex;
int weight;
struct ArcNode *next;
} ArcNode;
typedef struct {
int vertex;
ArcNode *firstarc;
} VertexNode;
void create_graph(Graph *G) {
int i, j, k, weight;
printf("请输入顶点数和边数:");
scanf("%d%d", &G->vertex_num, &G->edge_num);
for (i = 0; i < G->vertex_num; i++) {
printf("请输入第%d个顶点的值:", i + 1);
scanf("%d", &G->vertex[i]);
}
for (i = 0; i < G->vertex_num; i++) {
for (j = 0; j < G->vertex_num; j++) {
G->edge[i][j] = 0;
}
}
printf("请输入每条边的起点, 终点和权重:\n");
for (k = 0; k < G->edge_num; k++) {
scanf("%d%d%d", &i, &j, &weight);
G->edge[i - 1][j - 1] = weight;
}
}
void print_graph(Graph G) {
int i, j;
printf("邻接矩阵:\n");
for (i = 0; i < G.vertex_num; i++) {
for (j = 0; j < G.vertex_num; j++) {
printf("%d ", G.edge[i][j]);
}
printf("\n");
}
}
void generate_adjlist(Graph G, VertexNode adjlist[]) {
int i, j;
ArcNode *p;
for (i = 0; i < G.vertex_num; i++) {
adjlist[i].vertex = G.vertex[i];
adjlist[i].firstarc = NULL;
for (j = 0; j < G.vertex_num; j++) {
if (G.edge[i][j] != 0) {
p = (ArcNode *) malloc(sizeof(ArcNode));
p->vertex = G.vertex[j];
p->weight = G.edge[i][j];
p->next = adjlist[i].firstarc;
adjlist[i].firstarc = p;
}
}
}
}
void print_adjlist(VertexNode adjlist[], int n) {
int i;
ArcNode *p;
printf("邻接表:\n");
for (i = 0; i < n; i++) {
printf("%d: ", adjlist[i].vertex);
p = adjlist[i].firstarc;
while (p != NULL) {
printf("%d(%d) ", p->vertex, p->weight);
p = p->next;
}
printf("\n");
}
}
int main() {
Graph G;
VertexNode adjlist[MAX_VERTEX_NUM];
create_graph(&G);
print_graph(G);
generate_adjlist(G, adjlist);
print_adjlist(adjlist, G.vertex_num);
return 0;
}
```
阅读全文