简单实现
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 1024
// 边节点的定义
typedef struct _EdgeNode {
int adjvex; // 邻接的顶点
struct _EdgeNode *next; // 下一条边
} EdgeNode;
// 顶点节点的定义
typedef struct _VertexNode {
char data; // 节点数据
EdgeNode *first; // 指向邻接的第一条边
} VertexNode, AdjList[MaxSize];
// 图的定义
typedef struct _AdjListGraph {
AdjList adjlist;
int vex; // 顶点数
int edge; // 边数
} AdjListGraph;
/* 图的初始化 */
void Init(AdjListGraph *G) {
G->edge = 0;
G->vex = 0;
for (int i = 0; i < MaxSize; i++) {
G->adjlist[i].first = NULL;
}
}
/* 通过顶点对应的字符寻找顶点在图中的邻接点 */
int Location(AdjListGraph *G, char c) {
for (int i = 0; i < G->vex; i++) {
if (G->adjlist[i].data == c) {
return i;
}
}
return -1;
}
/* 图的创建 */
void Create(AdjListGraph *G) {
printf("请输入该图的顶点数以及边数:\n");
scanf("%d %d", &G->vex, &G->edge);
printf("请输入相关顶点:\n");
for (int i = 0; i < G->vex; i++) {
getchar(); // 吃掉换行符
scanf("%c", &G->adjlist[i].data);
G->adjlist[i].first = NULL;
}
char v1, v2; // 保存输入的顶点的字符
int i1, i2; // 保存顶点在数组中的下标
printf("请输入想关联边的顶点:\n");
for (int i = 0; i < G->edge; i++) {
getchar(); // 吃掉换行符
scanf("%c %c", &v1, &v2);
i1 = Location(G, v1);
i2 = Location(G, v2);
if (i1 != -1 && i2 != -1) { // 寻找到位置
EdgeNode *temp = (EdgeNode *)malloc(sizeof(EdgeNode));
temp->adjvex = i2;
temp->next = G->adjlist[i1].first;
G->adjlist[i1].first = temp;
}
}
}
/* 图的显示 */
void Display(AdjListGraph *G) {
for (int i = 0; i < G->vex; i++) {
printf("顶点 %c: ", G->adjlist[i].data);
EdgeNode *temp = G->adjlist[i].first;
while (temp) {
printf("-> %c ", G->adjlist[temp->adjvex].data);
temp = temp->next;
}
printf("\n");
}
}
int main() {
AdjListGraph G;
Init(&G);
Create(&G);
Display(&G); // 显示图的邻接表
// 这里可以添加更多的功能,比如图的遍历、显示等
return 0;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.
- 89.
- 90.
- 91.