本文实现了有向图的邻接表表示,并且实现了从创建到销毁图的各种操作。
以及深度优先遍历,广度优先遍历,Dijkstra最短路径算法,Prim最小生成树算法,拓扑排序算法。
可结合我的另一篇文章(有向图,无向图的邻接矩阵表示)看。
PS: 等有时间了作详细的讲解。
#include <iostream>
#include <climits>
#include <sstream>
#include <queue>
using namespace std;
//const bool UNDIGRAPH = 1;
struct EdgeNode//edge,the node of linked list
{
int vtxNO;
int weight;
EdgeNode *next;
};
struct VNode//vertex, the head of the linked list
{
string vertexLabel;
EdgeNode *first;
bool visited;//only for DFS,BFS,Dijkstra
int distance; //only for Dijkstra
int path;//only for Dijkstra
int indegree; //only for topological sort
};
struct Graph
{
VNode *vertexList;//the size of this array is equal to vertexes
int vertexes;
int edges;
};
void BuildGraph(Graph *&graph, int n)
{
if (graph == NULL)
{
graph = new Graph;
graph->vertexList = new VNode[n];
graph->vertexes = n;
graph->edges = 0;
for (int i = 0; i < n; i++)
{
stringstream ss;
ss<<"v" << i+1;
ss >> graph->vertexList[i].vertexLabel;
graph->vertexList[i].path = -1;
graph->vertexList[i].visited = false;
graph->vertexList[i].first = NULL;
graph->vertexList[i].indegree = 0;
}
}
}
void MakeEmpty(Graph *&graph)
{
if(graph == NULL)
return;
for (int i = 0; i < graph->vertexes; i++)
{
EdgeNode *pEdge = graph->vertexList[i].first;
while (pEdge!=NULL)
{
EdgeNode *tmp = pEdge;
pEdge = pEdge->next;
delete tmp;
}
}
delete graph;
}
void AddEdge(Graph *graph,int v1, int v2, int weight)
{
if (graph == NULL) return;
if (v1 < 0 || v1 > graph->vertexes-1) return;
if (v2 < 0 || v2 > graph->vertexes-1) return;
if (v1 == v2) return; //no loop is allowed
EdgeNode *p = graph->vertexList[v1].first;
if(p == NULL)
{
//can not be p = new EdgeNode;
graph->vertexList[v1].first = new EdgeNode;
graph->vertexList[v1].first->