C++实现 图Graph --- 邻接表
程序员文章站
2022-03-25 17:57:33
...
#include <iostream>
#include <list>
using namespace std;
template <class T>
class Graph
{
public:
Graph(int init = 5);
~Graph();
void addVertex(T&);
void printVertice();
void addEdge(int n, int element);
void printAdjList();
private:
int n;
int nVerts;
T* vertsList;
list<int>* Nodes;
};
template <class T>
Graph<T>::Graph(int init)
{
this->n = init;
this->nVerts = 0;
this->vertsList = new T[n];
this->Nodes = new list<int>[n];
}
template <class T>
Graph<T>::~Graph()
{
delete[] vertsList;
delete[] Nodes;
cout << endl << "~Graph() delete" << endl;
}
template <class T>
void Graph<T>::addVertex(T&t)
{
if (this->n < nVerts) throw " ";
this->vertsList[nVerts++] = t;
}
template <class T>
void Graph<T>::printVertice()
{
for (int i = 0; i < this->n; ++i)
{
cout << this->vertsList[i] << " ";
}
}
template <class T>
void Graph<T>::addEdge(int n, int element)
{
this->Nodes[n].push_back(element);
}
template <class T>
void Graph<T>::printAdjList()
{
for (int i = 0; i < this->n; ++i)
{
cout << endl << "第 " << i << " 个list<int>数的元素: ";
for (list<int>::iterator iter = Nodes[i].begin();
iter != Nodes[i].end(); ++iter)
{
cout << *iter << " ";
}
cout << endl;
}
}
int main()
{
Graph<char> gc;
char f('F');
char k('G');
char h('H');
char i('I');
char j('J');
gc.addVertex(f);
gc.addVertex(k);
gc.addVertex(h);
gc.addVertex(i);
gc.addVertex(j);
gc.addEdge(0, 1); gc.addEdge(0, 3);
gc.addEdge(1, 0); gc.addEdge(1, 4);
gc.addEdge(2, 4);
gc.addEdge(3, 0); gc.addEdge(3, 4);
gc.addEdge(4, 1); gc.addEdge(4, 2); gc.addEdge(4, 3);
cout << "Vertex :" << endl;
gc.printVertice();
cout << endl<<endl << "LIST :";
gc.printAdjList();
cout << endl << "ok" << endl;
return 0;
}