GeeksforGeeks - Adjacency List邻接矩阵C\C++代码

来源:互联网 发布:ad电路设计软件怎么样 编辑:程序博客网 时间:2024/05/18 03:44

邻接矩阵的图示:

Adjacency List Representation of Graph

构建一个这样的无向邻接矩阵。

参考网站: 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);}}};


下面是C++的代码,C++的代码会更加简洁。

使用默认构造函数和使用new的确会方便很多。

malloc原始快捷,new方便。不用专门设置一个create函数,直接new+构造函数就实现了。

#include <stdio.h>#include <stdlib.h>#include <iostream>class AdjListGraph_2{struct Node{int label;Node *next;Node(int l = 0, Node *n = nullptr) : label(l), next(n){}};struct Vertice{Node *first;Vertice() : first(nullptr) {}};struct Graph{int vers;Vertice *vArr;Graph(int v = 5) : vers(v){vArr = new Vertice[vers];}};Graph *graph;public:AdjListGraph_2(int V = 5) : graph(nullptr){graph = new Graph(V);addEdge(0, 1);addEdge(0, 4);addEdge(1, 2);addEdge(1, 3);addEdge(1, 4);addEdge(2, 3);addEdge(3, 4);printGraph();}void addEdge(int src, int dest){Node *n = new Node(dest);n->next = graph->vArr[src].first;graph->vArr[src].first = n;n = new Node(src);n->next = graph->vArr[dest].first;graph->vArr[dest].first = n;}void printGraph(){if (graph){for (int i = 0; i < graph->vers; i++){Node *n = graph->vArr[i].first;printf("\n The %d vertice's adjcences are :\n V%d", i, i);while (n){printf(" ->V%d", n->label);n = n->next;}putchar('\n');}}}~AdjListGraph_2(){if (graph){for (int i = 0; i < graph->vers; i++){Node *n = graph->vArr[i].first;while (n){Node *p = n;n = n->next;delete p;}}delete [] graph->vArr;delete graph;}}};



2 0
原创粉丝点击