邻接矩阵的图示:
构建一个这种无向邻接矩阵。
參考站点: 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(" Adjacency list of vertex %d head ", i); while (n) { printf("-> %d", n->dest); n = n->next; } putchar(' '); } } 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(" The %d vertice's adjcences are : V%d", i, i); while (n) { printf(" ->V%d", n->label); n = n->next; } putchar(' '); } } } ~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; } } };