邻接表
const int DefaultVertices = 30;
template<class T,class E>
struct Edge {
int dest;
E cost;
Edge<T, E>* link;
Edge() { dest = -1; cost = 0; link = NULL; }
Edge(int num, E weight) { dest = num; cost = weight; link = NULL; }
};
template<class T,class E>
struct Vertex {
T data;
Edge<T,E>* adj;
Vertex() {};
};
template<class T, class E>
class Graph
{
public:
int maxVertices;
int numEdges;
int numVertices;
bool* visited;
Vertex<T,E>* NodeTable;
Graph(int sz);
~Graph();
int getVertexPos(T vetrex) {
for (int i = 0; i < numVertices; i++) {
if (NodeTable[i].data == Vertex)return i;
}
return -1;
}
void CreateNodeTable();
void DFS(int v);
void BFS();
};
template<class T, class E>
Graph<T,E>::Graph(int sz ) {
maxVertices = sz; numVertices = 0; numEdges = 0;
NodeTable = new Vertex<T,E>[maxVertices];
visited = new bool[sz];
int i;
cout << " 请输入结点数 :" << endl;
cin >> numVertices;
if (NodeTable == NULL||visited == NULL)
{
cerr << "存储分配错误!" << endl;
exit(0);
}
for (i = 0; i < maxVertices; i++) {
NodeTable[i].adj = NULL;
}
for (i = 0; i < numVertices; i++)
{
visited[i] = false;
}
CreateNodeTable();
}
template<class T, class E>
Graph<T, E>::~Graph() {
Edge<T, E>* p;
for (int i = 0; i < numVertices; i++)
{
p = NodeTable[i].adj;
while (p != 0)
{
NodeTable[i].adj = p->link;
delete p;
p = NodeTable[i].adj;
}
}
}
template<class T, class E>
void Graph<T, E>::CreateNodeTable()
{
int n=0, j=0, i=0, m=0;
Edge<T, E>* p;
cout << "输入结点个数: " << endl;
cin >> n;
for (i = 0; i < n; i++)
{
NodeTable[i].adj = 0;
cout << "输入该结点的值" << endl ;
cin >> NodeTable[i].data;
cout << "输入相邻的结点个数 : " << endl;
cin >> m;
for (j = 0; j < m; j++)
{
p = new Edge<T, E>;
cout << "输入连接点的 数组下标号: " << endl;
cin >> p->dest;
p->link = NodeTable[i].adj;
NodeTable[i].adj = p;
}
}
}
template<class T, class E>
void Graph<T, E>::DFS(int v)
{
Edge<T, E> *p;
visited[v] = true;
cout << NodeTable[v].data<<" -> ";
p = NodeTable[v].adj;
while (p != 0)
{
if (!visited[p->dest])
DFS(p->dest);
p = p->link;
}
}
template<class T, class E>
void Graph<T, E>::BFS()
{
int v=0;
Edge<T, E>* p;
queue<int> qu;
cout << "输入一个出发点的位置:" << endl;
cin >> v;
qu.push(v);
visited[v] = true;
while (!qu.empty())
{
v = qu.front();
qu.pop();
cout << NodeTable[v].data<<" -> ";
p = NodeTable[v].adj;
while (p != 0)
{
qu.push(p->dest);
p = p->link;
}
}
}