链表实现的图存储及拓扑排序
注:本文内容为图的简易存储及拓扑排序,
标准版请查看[链表实现图存储及其遍历]
如下图所示,本文代码主要实现c图的结构,并基于该结构完成广度和深度优先排序。
代码如下:
#include<iostream>
#include<string>
#include<queue>
#include<stack>
#include<list>
#include<stdlib.h>
using namespace std;
typedef int Vertex;
template<int graph_size>
class Diagraph {
public:
Diagraph();
void read();
void write();
void depth_sort(list<Vertex> &topological_order);//深度优先递归拓扑排序
void depth_sort_stack(list<Vertex> &topological_order);//深度优先拓扑排序栈
void breadth_sort(list<Vertex> &topological_order);//广度优先拓扑排序
private:
int count;
list<Vertex> neighbors[graph_size]; //存放每个节点的后继
void recursive_depth_sort(Vertex v, bool visited[], list<Vertex> &topological_order);//递归排序
};
template<int graph_size> Diagraph<graph_size>::Diagraph() {
count = 0;
}
template<int graph_size>void Diagraph<graph_size>::read() {
cin >> count;
for (Vertex v = 0; v < count; v++) {
//输入count个节点
int degree = 0;
string c;
cout << "Vertex" << v << ":" << endl;
while (1) {
cin >> c; //输入后继节点
if (c[0] == '-') //输入-该节点输入结束
break;
int w = atoi(c.c_str()); //字符串转为int型
neighbors[v].push_back(w);