Earlier we had discussed in Graph Representation – Adjacency Matrix and Adjacency List about Graph and its different representations. In this article we will see the better (use inbuilt class of LinkedList) way to implement graph using adjacency list.

Let’s revise few basic concepts:

**What is Graph:**

*G = (V,E)*

Graph is a collection of nodes or vertices (V) and edges(E) between them. We can traverse these nodes using the edges. These edges might be weighted or non-weighted.

There can be two kinds of Graphs

- Un-directed Graph – when you can traverse either direction between two nodes.
- Directed Graph – when you can traverse only in the specified direction between two nodes.

Now how do we represent a Graph, There are two common ways to represent it:

- Adjacency Matrix
- Adjacency List

**Adjacency List:**

Adjacency List is the Array[] of Linked List, where array size is same as number of Vertices in the graph. Every Vertex has a Linked List. Each Node in this Linked list represents the reference to the other vertices which share an edge with the current vertex. The weights can also be stored in the Linked List Node.

**Complete Code for Graph Using Adjacency List:**

import java.util.LinkedList; | |

public class Graph { | |

int vertex; | |

LinkedList<Integer> list[]; | |

public Graph(int vertex) { | |

this.vertex = vertex; | |

list = new LinkedList[vertex]; | |

for (int i = 0; i <vertex ; i++) { | |

list[i] = new LinkedList<>(); | |

} | |

} | |

public void addEdge(int source, int destination){ | |

//add edge | |

list[source].addFirst(destination); | |

//add back edge ((for undirected) | |

list[destination].addFirst(source); | |

} | |

public void printGraph(){ | |

for (int i = 0; i <vertex ; i++) { | |

if(list[i].size()>0) { | |

System.out.print("Vertex " + i + " is connected to: "); | |

for (int j = 0; j < list[i].size(); j++) { | |

System.out.print(list[i].get(j) + " "); | |

} | |

System.out.println(); | |

} | |

} | |

} | |

public static void main(String[] args) { | |

Graph graph = new Graph(5); | |

graph.addEdge(0,1); | |

graph.addEdge(0, 4); | |

graph.addEdge(1, 2); | |

graph.addEdge(1, 3); | |

graph.addEdge(1, 4); | |

graph.addEdge(2, 3); | |

graph.addEdge(3, 4); | |

graph.printGraph(); | |

} | |

} |

**Output:**

Vertex 0 is connected to: 4 1 Vertex 1 is connected to: 4 3 2 0 Vertex 2 is connected to: 3 1 Vertex 3 is connected to: 4 2 1 Vertex 4 is connected to: 3 1 0