In: Computer Science
Since you have not mentioned the language of your preference, I am providing the code in JAVA.
CODE
import java.util.LinkedList;
public class AdjacencyList
{
static class Graph
{
int V;
LinkedList<Integer> adjListNodes[];
// constructor
Graph(int V)
{
this.V = V;
// define the size of array as
// number of vertices
adjListNodes = new LinkedList[V];
// Create a new list for each vertex
// such that adjacent nodes can be stored
for(int i = 0; i < V ; i++){
adjListNodes[i] = new LinkedList<>();
}
}
}
public static void addEdge(Graph graph, int src, int dest)
{
graph.adjListNodes[src].add(dest);
// Since this is an undirected graph, need to add an edge from dest to src too
graph.adjListNodes[dest].add(src);
}
public static void displayGraph(Graph graph)
{
for(int v = 0; v < graph.V; v++)
{
System.out.println("Adjacency list of vertex "+ v);
System.out.print("head");
for(Integer pCrawl: graph.adjListNodes[v]){
System.out.print(" -> "+pCrawl);
}
System.out.println("\n");
}
}
public static void main(String args[])
{
// create the graph given in above figure
int V = 5;
Graph graph = new Graph(V);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 2);
addEdge(graph, 1, 0);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);
displayGraph(graph);
}
}