代码和相关注释如下:
#include<iostream>
#include<cstring>
#include<math.h>
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
const int maxWeight = RAND_MAX; //无穷大的值
const int DefaultVertices = 30; //最大顶点数不妨设为30
template <class T, class E>
class Graph {
protected:
int maxVertices=10;//图中最大顶点数
int numVertices=0;//图中当前顶点数
int numEdges=0;//图中当前边数
bool direction=false;//图中边的是否有方向
bool withCost=false;//图中的边是否带权
//返回顶点名vertex的序号(从0开始)
int getVertexPos (T vertex);
public:
Graph(int sz , bool direct, bool cost); //构造函数
~Graph()//析构函数
{
}
//析构函数
bool GraphEmpty () const //判图是否为空,因为不需要修改,因此设置为常成员函数
{
return numEdges == 0;
}
bool GraphFull() const; //判图是否为满
//返回图中当前顶点数
int NumberOfVertices ()
{
return numVertices;
}
//返回图中当前边数
int NumberOfEdges ()
{
return numEdges;
}
//取回序号为 i 的顶点值(顶点名)
virtual T getValue (int i){
}
//取顶点序号为v1,v2的边上权值
virtual E getWeight (int v1, int v2){
}
//取顶点 v 的第一个邻接顶点序号
virtual int getFirstNeighbor (int v){
}
//返回顶点 v 和邻接顶点 w 的下一个邻接顶点序号
virtual int getNextNeighbor (int v, int w){
}
//插入新顶点, 点名为vertex
virtual bool insertVertex (const T vertex){
}
//插入新边(v1,v2), 权值cost
virtual bool insertEdge (T v1, T v2, E cost){
}
//删除名为 v 的顶点和所有与它相关联的边
virtual bool removeVertex (T v){
}
//在图中删除边(v1,v2)
virtual bool removeEdge (T v1, T v2){
}
};
template<class T , class E>
Graph<T,E>::Graph (int sz , bool direct, bool cost)
{
sz = DefaultVertices, direct=false, cost=false;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
template <class T, class E> //
class Edge_Vertices {
//边结点的类定义
public:
int dest; //边的邻接(终)点序号
E cost; //边上的权值
Edge_Vertices<T, E>* link;//下一个连接顶点
Edge_Vertices (int num=0, Edge_Vertices<T, E>* next=NULL, E weight=NULL) //构造函数
: dest (num), link (next), cost (weight) {
}
bool operator != (Edge_Vertices<T, E>& R) const
{
return dest != R.dest; } //重载!=运算符,判边不等
};
template <class T, class E>
class Vertex {
//顶点的类定义
public:
T data; //源顶点的名字(数据)
Edge_Vertices<T, E>* next=NULL; //next指针用来连接顶点
};
//邻接表图的类定义继承图类
template <class T, class E>
class Graphlnk : public Graph<T, E>{
public:
void Enter (void); //输入图中顶点和边信息
void Print (void); //输出图中顶点和边信息
//源顶点表 (各边链表的源顶点)
Vertex<T, E>* NodeTable;
//返回名为vertex的顶点在图中的序号(从0开始),
//若未找到,则返回-1
int getVertexPos (const T vertx