一、思路:
有向图的插入有向边、删除边、删除顶点和无向图的有区别。其他的和无向图的类似。
1.插入有向边<e1, e2>
只需要插入<e1, e2>边就行,不需要插入对称边<e2, e1>
2.删除边<e1,e2>:
只需要删除<e1, e2>边就行,不需要仔找对称边<e2, e1>进行删除。
3.删除顶点v:
首先,要在邻接表中删除以v为头的边<v, w>;
同时,也要在邻接表中删除以v为尾的边<k, v>, 不能通过对称边来找,只能一个个顶点找,浪费时间。
二、实现程序:
1.DirectedGraph.h:有向图
#ifndef DirectedGraph_h
#define DirectedGraph_h
#include <iostream>
using namespace std;
const int DefaultVertices = 30;
template <class T, class E>
struct Edge { // 边结点的定义
int dest; // 边的另一顶点位置
E cost; // 表上的权值
Edge<T, E> *link; // 下一条边链指针
};
template <class T, class E>
struct Vertex { // 顶点的定义
T data; // 顶点的名字
Edge<T, E> *adj; // 边链表的头指针
};
template <class T, class E>
class Graphlnk {
public:
const E maxValue = 100000; // 代表无穷大的值(=∞)
Graphlnk(int sz=DefaultVertices); // 构造函数
~Graphlnk(); // 析构函数
void inputGraph(); // 建立邻接表表示的图
void outputGraph(); // 输出图中的所有顶点和边信息
T getValue(int i); // 取位置为i的顶点中的值
E getWeight(int v1, int v2); // 返回边(v1, v2)上的权值
bool insertVertex(const T& vertex); // 插入顶点
bool insertEdge(int v1, int v2, E weight); // 插入边
bool removeVertex(int v); // 删除顶点
bool removeEdge(int v1, int v2); // 删除边
int getFirstNeighbor(int v); // 取顶点v的第一个邻接顶点
int getNextNeighbor(int v,int w); // 取顶点v的邻接顶点w的下一邻接顶点
int getVertexPos(const T vertex); // 给出顶点vertex在图中的位置
int numberOfVertices(); // 当前顶点数
private:
int maxVertices; // 图中最大的顶点数
int numEdges; // 当前边数
int numVertices; // 当前顶点数
Vertex<T, E> * nodeTable; // 顶点表(各边链表的头结点)
};
// 构造函数:建立一个空的邻接表
template <class T, class E>
Graphlnk<T, E>::Graphlnk(int sz) {
maxVertices = sz;
numVertices = 0;
numEdges = 0;
nodeTable = new Vertex<T, E>[maxVertices]; // 创建顶点表数组
if(nodeTable == NULL) {
cerr << "存储空间分配错误!" << endl;
exit(1);
}
for(int i = 0; i < maxVertices; i++)
nodeTable[i].adj = NULL;
}
// 析构函数
template <class T, class E>
Graphlnk<T, E>::~Graphlnk() {
// 删除各边链表中的结点
for(int i = 0; i < numVertices; i++)