Copy Code code as follows:
#include <iostream>
#include <list>
#include <stack>
using namespace Std;
Class Graph {
int vertexnum;
List<int> *adjacents;
Public
Graph (int _vertexnum) {
Vertexnum = _vertexnum;
adjacents = new list<int>[vertexnum];
}
void Findindegree (int *indegree, int n);
BOOL Topologicalsort ();
void Addedge (int v, int w);
};
void Graph::addedge (int v, int w) {
Adjacents[v].push_back (w);
}
void Graph::findindegree (int *indegree, int n) {
int v;
list<int>::iterator ITER;
for (v = 0; v < vertexnum; v++) {
for (iter = Adjacents[v].begin (); Iter!= adjacents[v].end (); iter++)
indegree[*iter]++;
}
}
BOOL Graph::topologicalsort () {
int ver_count = 0;
stack<int> M_stack;
int *indegree = new Int[vertexnum];
memset (indegree, 0, sizeof (int) * vertexnum);
findindegree (Indegree, vertexnum);
int v;
for (v = 0; v < vertexnum; v++)
if (0 = = Indegree[v])
m_stack.push (v); Br> while (!m_stack.empty ()) {
v = M_stack.top ();
m_stack.pop ();
cout << v << "";
ver_count++;
for (List<int>::iterator iter = Adjacents[v].begin (); Iter!= adjacents[v].end (); iter++) {
& Nbsp; if (0 =--indegree[*iter])
m_stack.push (*iter);
&NBSP;&NBSP}
}
cout << Endl;
if (Ver_count < Vertexnum)
return false;
return true;
}
int main (int argc, char *argv[]) {
Graph g (6);
G.addedge (5, 2);
G.addedge (5, 0);
G.addedge (4, 0);
G.addedge (4, 1);
G.addedge (2, 3);
G.addedge (3, 1);
if (G.topologicalsort ())
cout << "It is a topological graph" << Endl;
Else
cout << "It is not a topological graph" << Endl;
Cin.get ();
return 0;
}