Skip to content

Commit 34483e9

Browse files
authored
Merge pull request #103 from madhav1928/main
Add files via upload
2 parents e8f7b40 + 7a0f2dc commit 34483e9

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

TopologicalSorting.java

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import java.util.*;
2+
class Graph{
3+
int v;
4+
LinkedList<Integer> adj[];
5+
@SuppressWarnings("unchecked")
6+
Graph(int v){
7+
this.v=v;
8+
adj=new LinkedList[v];
9+
for(int i=0;i<v;i++)
10+
adj[i]=new LinkedList<>();
11+
}
12+
}
13+
class TopologicalSorting{
14+
public static void addEdge(Graph g,int u,int v){
15+
g.adj[u].add(v);
16+
}
17+
public static void toposortutil(Graph g,int node,boolean visit[],Stack st)
18+
{
19+
visit[node]=true;
20+
int i;
21+
Iterator<Integer>it=g.adj[node].iterator();
22+
while(it.hasNext())
23+
{
24+
i=it.next();
25+
System.out.println(i);
26+
if(!visit[i])
27+
toposortutil(g,i,visit,st);
28+
}
29+
System.out.println("node"+node);
30+
st.push(node);
31+
}
32+
public static void toposort(Graph g){
33+
Stack st=new Stack();
34+
boolean visit[]=new boolean[g.v];
35+
for(int i=0;i<g.v;i++)
36+
if(visit[i]==false)
37+
toposortutil(g,i,visit,st);
38+
while(st.empty()==false)
39+
System.out.println(st.pop()+" ");
40+
}
41+
public static void main(String[] args){
42+
Graph g = new Graph(6);
43+
TopologicalSorting tp=new TopologicalSorting();
44+
tp.addEdge(g,5, 2);
45+
tp.addEdge(g,5, 0);
46+
tp.addEdge(g,4, 0);
47+
tp.addEdge(g,4, 1);
48+
tp.addEdge(g,2, 3);
49+
tp.addEdge(g,3, 1);
50+
tp.toposort(g);
51+
}
52+
}
53+

0 commit comments

Comments
 (0)