Posted on by Kalkicode
Code Graph

Adjacency list representation of directed graph in java

Java program for Adjacency list representation of directed graph. Here problem description and explanation.

``````/*
Java Program for
Directed graph representation using adjacency list
*/
class AjlistNode
{
// Vertices node key
public int id;
public AjlistNode next;
public AjlistNode(int id)
{
// Set value of node key
this.id = id;
this.next = null;
}
}
class Vertices
{
public int data;
public AjlistNode next;
public AjlistNode last;
public Vertices(int data)
{
this.data = data;
this.next = null;
this.last = null;
}
}
public class Graph
{
// Number of Vertices
public int size;
public Vertices[] node;
public Graph(int size)
{
// Set value
this.size = size;
this.node = new Vertices[size];
this.setData();
}
// Set initial node value
public void setData()
{
if (size <= 0)
{
System.out.println("\nEmpty Graph");
}
else
{
for (int index = 0; index < size; index++)
{
// Set initial node value
node[index] = new Vertices(index);
}
}
}
// Connect two nodes
public void connect(int start, int last)
{
AjlistNode edge = new AjlistNode(last);
if (node[start].next == null)
{
node[start].next = edge;
}
else
{
// Add edge at the end
node[start].last.next = edge;
}
// Get last edge
node[start].last = edge;
}
//  Handling the request of adding new edge
public void addEdge(int start, int last)
{
if (start >= 0 && start < size &&
last >= 0 && last < size )
{
// Safe connection
connect(start, last);
}
else
{
// When invalid nodes
System.out.println("\nHere Something Wrong");
}
}
public void printGraph()
{
if (size > 0 )
{
// Print graph ajlist Node value
for (int index = 0; index < size; ++index)
{
System.out.print("\nAdjacency list of vertex " + index + " :");
AjlistNode temp = node[index].next;
while (temp != null)
{
// Display graph node
System.out.print("  " + node[temp.id].data);
// visit to next edge
temp = temp.next;
}
}
}
}
public static void main(String[] args)
{
// 5 implies the number of nodes in graph
Graph g = new Graph(5);
// Connect node with an edge
// print graph element
g.printGraph();
}
}``````

Output

``````Adjacency list of vertex 0 :  1
Adjacency list of vertex 1 :  2  4
Adjacency list of vertex 2 :  0  3
Adjacency list of vertex 3 :
Adjacency list of vertex 4 :  3``````

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

Categories
Relative Post