# Graph Implementation – Adjacency List – Better| Set 2

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 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 list[]; public Graph(int vertex) { this.vertex = vertex; list = new LinkedList[vertex]; for (int i = 0; i (); } } 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 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(); } }

view raw
Graph.java
hosted with ❤ by GitHub

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```