图(有向图)的邻接表表示 C++实现(遍历,拓扑排序,最短路径,最小生成树) Implement of digraph and undigraph using adjacency list

本文实现了有向图的邻接表表示,并且实现了从创建到销毁图的各种操作。

以及深度优先遍历,广度优先遍历,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->
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值