Question: (explain this code please) class Graph { private int V; // No. of vertices // Array of lists for Adjacency List Representation private LinkedList adj[];

(explain this code please)
class Graph
{
private int V; // No. of vertices
// Array of lists for Adjacency List Representation
private LinkedList adj[];
// Constructor
Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i=0; i
adj[i] = new LinkedList();
} //initialize the list with 0 values.
}
// Function to add an edge into the graph
void addEdge(int v, int w) { adj[v].add(w); }
// A recursive function used by topologicalSort
void topologicalSortUtil(int v, boolean visited[], Stack stack) {
// Mark the current node as visited.
visited[v] = true;
Integer i;
// Recur for all the vertices adjacent to this vertex
Iterator it = adj[v].iterator();
while (it.hasNext()) {
i = it.next();
if (!visited[i]) { topologicalSortUtil(i, visited, stack); }
} // Push current vertex to stack which stores result //push the element in stack after recursion ends.
stack.push(new Integer(v)); } // The function to do Topological Sort. It uses recursive //topological sort function call from here.
void topologicalSort() {
Stack stack = new Stack();
boolean visited[] = new boolean[V];
for (int i = 0; i < V; i++)
visited[i] = false;
// Call the recursive helper
// function to store
// Topological Sort starting
// from all vertices one by one
for (int i = 0; i < V; i++)
if (visited[i] == false)
topologicalSortUtil(i, visited, stack);
// Print contents of stack
while (stack.empty() == false)
System.out.print(stack.pop() + " ");
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!