邻接表建立图
Posted yang901112
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了邻接表建立图相关的知识,希望对你有一定的参考价值。
使用邻接表建立图,直接使用了c++已经写好的list
1 #include <iostream> 2 #include <list> 3 4 using namespace std; 5 6 class Vertex 7 { 8 public: 9 char Label; 10 Vertex(char lab) {Label = lab;} 11 }; 12 13 ostream& operator<<(ostream& out, const Vertex& v) 14 { 15 cout << v.Label; 16 return out; 17 } 18 19 template<class T> 20 class Graph 21 { 22 public: 23 Graph(const int vertices):n(vertices) 24 { 25 VertexList = new T*[n]; 26 HeadNode = new list<int>[n]; 27 nVerts = 0; 28 } 29 ~Graph() 30 { 31 delete[] VertexList; 32 delete[] HeadNode; 33 } 34 void addVertex(T* v); 35 void addEdge(int start, int End); 36 void printVertice(); 37 void printAdjList(); 38 private: 39 T** VertexList; 40 list<int>* HeadNode; 41 int n; 42 int nVerts; 43 }; 44 45 template<class T> 46 void Graph<T>::addVertex(T* v) 47 { 48 VertexList[nVerts++] = v; 49 } 50 51 template<class T> 52 void Graph<T>::addEdge(int start, int End) 53 { 54 HeadNode[start].push_back(End); 55 } 56 57 template<class T> 58 void Graph<T>::printVertice() 59 { 60 for(int i=0; i<nVerts; i++) 61 cout << *VertexList[i] << " "; 62 cout << endl; 63 } 64 65 template<class T> 66 void Graph<T>::printAdjList() 67 { 68 for(int i=0; i<nVerts; i++) 69 { 70 cout << i << "->"; 71 for(list<int>::iterator iter = HeadNode[i].begin(); 72 iter != HeadNode[i].end(); ++iter) 73 cout << *iter << "->" ; 74 cout << "end" << endl; 75 } 76 } 77 78 int main() 79 { 80 // Graph<char> g(5); 81 // char a = ‘A‘; 82 // char b = ‘B‘; 83 // char c = ‘C‘; 84 // char d = ‘D‘; 85 // char e = ‘E‘; 86 Graph<Vertex> g(5); 87 Vertex a(‘A‘); 88 Vertex b(‘B‘); 89 Vertex c(‘C‘); 90 Vertex d(‘D‘); 91 Vertex e(‘E‘); 92 93 g.addVertex(&a); 94 g.addVertex(&b); 95 g.addVertex(&c); 96 g.addVertex(&d); 97 g.addVertex(&e); 98 99 g.addEdge(0,1); 100 g.addEdge(0,3); 101 g.addEdge(1,0); 102 g.addEdge(1,4); 103 g.addEdge(2,4); 104 g.addEdge(3,0); 105 g.addEdge(3,4); 106 g.addEdge(4,1); 107 g.addEdge(4,2); 108 g.addEdge(4,3); 109 g.printVertice(); 110 g.printAdjList(); 111 cout << "Hello world!" << endl; 112 return 0; 113 }
以上是关于邻接表建立图的主要内容,如果未能解决你的问题,请参考以下文章