CopyCode The Code is 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 );
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 ++ ){
If (0 = -- indegree [* ITER])
M_stack.push (* ITER );
}
}
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" else
cout <"it is not a topological graph" cin. get ();
return 0;
}