首页 > 代码库 > GeeksforGeeks - Adjacency List邻接矩阵C代码
GeeksforGeeks - Adjacency List邻接矩阵C代码
邻接矩阵的图示:
构建一个这样的无向邻接矩阵。
参考网站: http://www.geeksforgeeks.org/graph-and-its-representations/
这里写了个类,增加删除图的操作。
#pragma once #include <stdio.h> #include <stdlib.h> class AdjListGraph { struct Node { int dest; Node *next; }; struct List { Node *first; }; struct Graph { int vers; List *verArr; }; Node *createNode(int dest) { Node *newNode = (Node *) malloc(sizeof(Node)); newNode->dest = dest; newNode->next = nullptr; return newNode; } Graph *createGraph(int vers) { Graph * gra = (Graph *) malloc(sizeof(Graph)); gra->vers = vers; gra->verArr = (List *) malloc(vers * sizeof(List)); for (int i = 0; i < vers; i++) { gra->verArr[i].first = nullptr; } return gra; } void addEdge(Graph *gra, int src, int dest) { Node *n = createNode(dest); n->next = gra->verArr[src].first;//这里不需要->next,因为无空head指针 gra->verArr[src].first = n; //构造无向图 n = createNode(src); n->next = gra->verArr[dest].first; gra->verArr[dest].first = n; } void printGraph() { for (int i = 0; i < graph->vers; i++) { Node *n = graph->verArr[i].first; printf("\n Adjacency list of vertex %d\n head ", i); while (n) { printf("-> %d", n->dest); n = n->next; } putchar(‘\n‘); } } Graph *graph; public: AdjListGraph(int V = 0) : graph(nullptr) { graph = createGraph(V); 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(); } ~AdjListGraph() { if (graph) { for (int i = 0; i < graph->vers; i++) { Node *n = graph->verArr[i].first; Node *p = nullptr; while (n) { p = n; n = n->next; free(p); } } free(graph->verArr); free(graph); } } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。