2️⃣3️⃣ 邻接表
😝 第一次接触类模板,迭代器,很新奇,希望以后能够慢慢理解,慢慢化为己用。
#include <iostream>
#include <list>
using namespace std;
class Vertex
{
public:
char Label;
Vertex(char lab):Label(lab) {}
};
ostream& operator << (ostream& out, const Vertex& v){
cout << v.Label;
return out;
}
template<class T>
class Graph
{
public:
Graph(const int vertices): n(vertices) ,nVerts(0) {
VertexList = new T* [n];
HeadNodes = new list<int>[n];
}
~Graph(){
delete[] VertexList;
delete[] HeadNodes;
}
void addVertex(T* v);
void addEdge(int start, int end);
void printVertice();
void printAdjList();
private:
T** VertexList;
list<int>* HeadNodes;
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){
HeadNodes[start].push_back(end);
}
template<class T>
void Graph<T>::printVertice(){
for(int i=0; i!=nVerts; i++)
cout << *VertexList[i] << " ";
cout << endl;
}
template<class T>
void Graph<T>::printAdjList(){
for(int i=0; i!=nVerts; i++){
cout << i << "->";
for(list<int>::iterator iter = HeadNodes[i].begin(); iter!=HeadNodes[i].end(); iter++)
cout << *iter << "->";
cout << "end" << endl;
}
}
int main()
{
Graph<Vertex> g(5);
Vertex a('A');
Vertex b('B');
Vertex c('C');
Vertex d('D');
Vertex e('E');
g.addVertex(&a);
g.addVertex(&b);
g.addVertex(&c);
g.addVertex(&d);
g.addVertex(&e);
g.printVertice();
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.printAdjList();
return 0;
}