Java Program to Describe the Representation of Graph using Adjacency List

This Java program,represents a given graph in the form of Adjacency list.

Here is the source code of the Java program to display a linked list in reverse. The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
 
public class GraphAdjacencyList 
{
   /* Makes use of Map collection to store the adjacency list for each vertex.*/
    private  Map<Integer, List<Integer>> Adjacency_List;	
   /*
    * Initializes the map to with size equal to number of vertices in a graph
    * Maps each vertex to a given List Object 
    */
    public GraphAdjacencyList(int number_of_vertices)
    {
        Adjacency_List = new HashMap<Integer, List<Integer>>();	
        for (int i = 1 ; i <= number_of_vertices ; i++)
        { 
            Adjacency_List.put(i, new LinkedList<Integer>());
        }
    }
 
 
    /* Adds nodes in the Adjacency list for the corresponding vertex */
    public void setEdge(int source , int destination)
    {
       if (source > Adjacency_List.size() || destination > Adjacency_List.size())
       {
           System.out.println("the vertex entered in not present ");
           return;
       }
       List<Integer> slist = Adjacency_List.get(source);
       slist.add(destination);
       List<Integer> dlist = Adjacency_List.get(destination);
       dlist.add(source);
   }
 
   /* Returns the List containing the vertex joining the source vertex */		
    public List<Integer> getEdge(int source)
    {
        if (source > Adjacency_List.size())
        {
            System.out.println("the vertex entered is not present");
            return null;
        }
        return Adjacency_List.get(source);
    }
 
    /*
     * Main Function reads the number of vertices and edges in a graph.
     * then creates a Adjacency List for the graph and prints it  
     */
     public static void main(String...arg)
     {
         int source , destination;
         int number_of_edges,number_of_vertices;
         int count = 1;
         Scanner scan = new Scanner(System.in);
         try
         {
             /* Read the number of vertices and edges in graph */
             System.out.println("Enter the number of vertices and edges in graph");
             number_of_vertices = scan.nextInt();
             number_of_edges = scan.nextInt();
             GraphAdjacencyList adjacencyList = new GraphAdjacencyList(number_of_vertices);
 
             /* Reads the edges present in the graph */
             System.out.println("Enter the edges in graph Format : <source index> <destination index>");
             while (count <= number_of_edges)
             {
                 source = scan.nextInt();
                 destination = scan.nextInt();
                 adjacencyList.setEdge(source, destination);
                 count++;
             }
 
             /* Prints the adjacency List representing the graph.*/
             System.out.println ("the given Adjacency List for the graph \n");
             for (int i = 1 ; i <= number_of_vertices ; i++)
             {
                 System.out.print(i+"->");
                 List<Integer> edgeList = adjacencyList.getEdge(i);
                 for (int j = 1 ; ; j++ )
                 {
                     if (j != edgeList.size())
                     {
                         System.out.print(edgeList.get(j - 1 )+"->");
                     }else
                     {
                         System.out.print(edgeList.get(j - 1 ));
                         break;
                     }						 
                 }
                 System.out.println();					
              }
          } 
          catch(InputMismatchException inputMismatch)
          {
              System.out.println("Error in Input Format. \nFormat : <source index> <destination index>");
          }
          scan.close();
     }
}
$javac GraphAdjacencyList.java
$java GraphAdjacencyList
Enter the number of vertices and edges in graph
4 5
Enter the edges in graph Format : <source index> <destination index>
1 2
2 3
3 4
4 1
1 3
the given Adjacency List for the graph 
 
1->2->4->3
2->1->3
3->2->4->1
4->3->1

Related posts:

Java Program to Perform Right Rotation on a Binary Search Tree
Java Program to Implement Strassen Algorithm
Java – Rename or Move a File
Java Program to Perform the Unique Factorization of a Given Number
Java Program to Find the Vertex Connectivity of a Graph
Java Program to Perform Complex Number Multiplication
So sánh ArrayList và Vector trong Java
Guide to DelayQueue
Java Program to Implement Suffix Tree
Map Interface trong java
Java Program to Implement Wagner and Fisher Algorithm for online String Matching
Jackson vs Gson
Remove HTML tags from a file to extract only the TEXT
Java Program to Implement ConcurrentLinkedQueue API
Java Program to Check Whether an Input Binary Tree is the Sub Tree of the Binary Tree
Spring Cloud – Bootstrapping
Guide to UUID in Java
Java Program to Generate All Subsets of a Given Set in the Lexico Graphic Order
Java Program to Implement Repeated Squaring Algorithm
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Performance Difference Between save() and saveAll() in Spring Data
Sao chép các phần tử của một mảng sang mảng khác như thế nào?
Java Program to Perform Insertion in a 2 Dimension K-D Tree
Java Program to Implement Network Flow Problem
Java – Random Long, Float, Integer and Double
New Features in Java 10
Add Multiple Items to an Java ArrayList
Java Program to Solve a Matching Problem for a Given Specific Case
Spring’s RequestBody and ResponseBody Annotations
Spring Boot - Tomcat Port Number
Limiting Query Results with JPA and Spring Data JPA