Here we will assume the vertices are from 0 to n-1. Below is the code for adjacency list representation of an undirected graph:
import java.util.LinkedList; class Graph { private int V; // No. of vertices private final boolean isDirected; private LinkedList<Integer> adj[]; //Adjacency List array //Constructor Graph(int v) { this(v, false); } Graph(int v, boolean isDirected) { V = v; adj = new LinkedList[v]; for (int i = 0; i<v; ++i) { adj[i] = new LinkedList(); } isDirected = isDirected; } //Function to add an edge into the graph void addEdge(int src, int dest) { adj[src].add(dest); // Since graph is undirected, add an edge from dest // to src also if (!isDirected) { adj[dest].add(src); } } void printGraph() { for (int v = 0; v<V; v++) { System.out.println("Adjacency list of vertex " + v); System.out.print("head"); for (Integer pCrawl: adj[v]) { System.out.print(" -> " + pCrawl); } System.out.println("\n"); } } // Driver method public static void main(String args[]) { // Create a graph given in the above diagram Graph g = new Graph(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(3, 4); System.out.println("Following are strongly connected components " + "in given graph "); } } public class GFG { // Driver program to test above functions public static void main(String args[]) { // create the graph given in above figure int V = 5; //undirected graph Graph graph = new Graph(V); addEdge(graph, 0, 1); addEdge(graph, 0, 4); addEdge(graph, 1, 2); addEdge(graph, 1, 3); addEdge(graph, 1, 4); addEdge(graph, 2, 3); addEdge(graph, 3, 4); // print the adjacency list representation of // the above graph printGraph(graph); } } ...