邻接表存储图信息思路
代码实现
编写结构体
从图结构体开始编写,成员信息要包括图中顶点的个数,边的个数,图的类型,以及一个数组vex,存储每一个顶点。这里的数组用vertexList*指针的形式表示,malloc申请空间的时候,根据顶点的个数控制空间大小。
接着编写顶点结构体,成员信息要包括该顶点的信息data,也就是顶点的表示信息,我们这里用数组对应下标表示该信息,还有一个指向表结点的指针,也就是邻接表,用来表示该顶点的邻接表,达到遍历某一顶点中邻接表的所有元素的效果。
接着编写表结点结构体,成员信息包括该顶点的信息,上一顶点到该顶点的边的权值,以及指向下一表结点的指针。
编写 创建表结点的函数
在代码的编写过程中,需要反复创建新的表节点,该函数中的代码需要大量重复使用,故将此写成函数,简化代码。
编写初始化函数
编写建图函数(插入邻接表)
编写展示图结构的函数
编写主函数
完整代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum graphType {DG, UG, DN, UN}; //图的类型定义:有向图,无向图,有向网,无项网
typedef char vertexType;
typedef struct node {
vertexType data;
int weight;
struct node* next;
}node;
typedef struct vertex {
vertexType data;
node* adjacencyList;
}vertexList;
typedef struct {
vertexList* vexs;
int vexnum, arcnum;
graphType kind;
} graph;
node* buyNewNode(int indexVertex,int weight){
node* newNode=(node*)malloc(sizeof(node));
newNode->data=indexVertex;
newNode->weight=weight;
newNode->next=NULL;
return newNode;
}
void initGraph(graph &g){
g.kind = UN;
printf("输入顶点数和边数:\n");
scanf("%d%d", &g.vexnum, &g.arcnum);
g.vexs=(vertexList*)malloc(sizeof(vertexList)*(g.vexnum+1));
for (int i = 1; i <= g.vexnum; i++) {
g.vexs[i].data =i ;
g.vexs[i].adjacencyList=NULL;
}
}
void createGraph(graph &g) {
int start_index, end_index, weight;
printf("输入每条边的起点终点下标和边的权重:\n");
for (int i = 1; i <= g.arcnum; i++) {
scanf("%d%d%d", &start_index, &end_index, &weight);
node* newnode=buyNewNode(end_index,weight);
newnode->next=g.vexs[start_index].adjacencyList;
g.vexs[start_index].adjacencyList=newnode;
newnode=buyNewNode(start_index,weight);
newnode->next=g.vexs[end_index].adjacencyList;
g.vexs[end_index].adjacencyList=newnode;
}
}
void showGraph(graph &g) {
for (int i = 1; i <= g.vexnum; i++) {
node* current = g.vexs[i].adjacencyList;
printf("顶点 %d 的邻接表:", i);
while (current != NULL) {
printf(" %d", current->data);
current = current->next;
}
printf("\n");
}
}
int main() {
graph g;
initGraph(g);
createGraph(g);
showGraph(g);
}
/*测试用例:
5 8
1 2 1
1 5 4
1 3 3
2 4 2
4 5 4
3 4 1
2 3 2
3 5 1
*/
代码运行截图:
可以验证,用邻接表表示出来的图是没有问题的。
结尾
我们今天学习了邻接表存储图信息,需要三个结构体,第一个是图的结构体,第二个是顶点结构体,第三个是表结构体(也是表示顶点)。第二个和第三个结构体都是用来存储顶点,但是需要区分的开来的原因是第三个结构体还存储上一顶点到该顶点的边的权值。图结构体中有一个数组存储各顶点你结构体,顶点结构体中有一个邻接表。
最后,感谢您阅读我的文章,希望这些内容能够对您有所启发和帮助。如果您有任何问题或想要分享您的观点,请随时在评论区留言。
同时,不要忘记订阅我的博客以获取更多有趣的内容。在未来的文章中,我将继续探讨这个话题的不同方面,为您呈现更多深度和见解。
谢谢您的支持,期待与您在下一篇文章中再次相遇!