C++資料結構 22 圖-鄰接表
阿新 • • 發佈:2018-11-24
#include <iostream> #include <list> using namespace std; class Vertex { }; template<class T> class Graph { public: Graph(const int vertices):n(vertices) { VertexList=new T*[n]; HeadList=new list<int>[n]; nVerts=0; } ~Graph() { delete []VertexList; delete []HeadList; } void addVertex(T* v); void addEdge(int Start,int End); void PrintVertex(); //列印頂點 void Printadjst(); //列印圖表 private: T** VertexList; //陣列 儲存連結串列 list<int>*HeadList; //陣列儲存頂點 int n; //最大的頂點 int nVerts; //當前頂點 }; template<class T> void Graph<T>::addVertex(T* v) //增加一個頂點 { VertexList[nVerts++]=v; } template<class T> void Graph<T>::addEdge(int Start,int End) //增加一條邊 { HeadList[Start].push_back(End); } template<class T> void Graph<T>::PrintVertex() //列印 { for(int i=0;i<nVerts;i++) cout<<*VertexList[i]<<" "; cout<<endl; } template<class T> void Graph<T>::Printadjst() //列印連結串列 { for(int i=0;i<nVerts;i++) { cout<<i<<"->"; for(list<int>::iterator iter=HeadList[i].begin();iter!=HeadList[i].end();iter++) cout<<*iter<<"->"; cout<<endl; } } int main() { Graph<char> g(5); char a='A'; char b='B'; char c='C'; char d='D'; char e='E'; g.addVertex(&a); g.addVertex(&b); g.addVertex(&c); g.addVertex(&d); g.addVertex(&e); g.PrintVertex(); g.addEdge(0,1); g.addEdge(0,3); g.addEdge(1,0); g.addEdge(1,4); g.addEdge(2,4); g.addEdge(3,0); g.addEdge(3,4); g.addEdge(4,1); g.addEdge(4,2); g.addEdge(4,3); g.Printadjst(); //cout << "Hello world!" << endl; return 0; }