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.

  1. import java.util.HashMap;
  2. import java.util.InputMismatchException;
  3. import java.util.LinkedList;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.Scanner;
  7.  
  8. public class GraphAdjacencyList 
  9. {
  10.    /* Makes use of Map collection to store the adjacency list for each vertex.*/
  11.     private  Map<Integer, List<Integer>> Adjacency_List;	
  12.    /*
  13.     * Initializes the map to with size equal to number of vertices in a graph
  14.     * Maps each vertex to a given List Object 
  15.     */
  16.     public GraphAdjacencyList(int number_of_vertices)
  17.     {
  18.         Adjacency_List = new HashMap<Integer, List<Integer>>();	
  19.         for (int i = 1 ; i <= number_of_vertices ; i++)
  20.         { 
  21.             Adjacency_List.put(i, new LinkedList<Integer>());
  22.         }
  23.     }
  24.  
  25.  
  26.     /* Adds nodes in the Adjacency list for the corresponding vertex */
  27.     public void setEdge(int source , int destination)
  28.     {
  29.        if (source > Adjacency_List.size() || destination > Adjacency_List.size())
  30.        {
  31.            System.out.println("the vertex entered in not present ");
  32.            return;
  33.        }
  34.        List<Integer> slist = Adjacency_List.get(source);
  35.        slist.add(destination);
  36.        List<Integer> dlist = Adjacency_List.get(destination);
  37.        dlist.add(source);
  38.    }
  39.  
  40.    /* Returns the List containing the vertex joining the source vertex */		
  41.     public List<Integer> getEdge(int source)
  42.     {
  43.         if (source > Adjacency_List.size())
  44.         {
  45.             System.out.println("the vertex entered is not present");
  46.             return null;
  47.         }
  48.         return Adjacency_List.get(source);
  49.     }
  50.  
  51.     /*
  52.      * Main Function reads the number of vertices and edges in a graph.
  53.      * then creates a Adjacency List for the graph and prints it  
  54.      */
  55.      public static void main(String...arg)
  56.      {
  57.          int source , destination;
  58.          int number_of_edges,number_of_vertices;
  59.          int count = 1;
  60.          Scanner scan = new Scanner(System.in);
  61.          try
  62.          {
  63.              /* Read the number of vertices and edges in graph */
  64.              System.out.println("Enter the number of vertices and edges in graph");
  65.              number_of_vertices = scan.nextInt();
  66.              number_of_edges = scan.nextInt();
  67.              GraphAdjacencyList adjacencyList = new GraphAdjacencyList(number_of_vertices);
  68.  
  69.              /* Reads the edges present in the graph */
  70.              System.out.println("Enter the edges in graph Format : <source index> <destination index>");
  71.              while (count <= number_of_edges)
  72.              {
  73.                  source = scan.nextInt();
  74.                  destination = scan.nextInt();
  75.                  adjacencyList.setEdge(source, destination);
  76.                  count++;
  77.              }
  78.  
  79.              /* Prints the adjacency List representing the graph.*/
  80.              System.out.println ("the given Adjacency List for the graph \n");
  81.              for (int i = 1 ; i <= number_of_vertices ; i++)
  82.              {
  83.                  System.out.print(i+"->");
  84.                  List<Integer> edgeList = adjacencyList.getEdge(i);
  85.                  for (int j = 1 ; ; j++ )
  86.                  {
  87.                      if (j != edgeList.size())
  88.                      {
  89.                          System.out.print(edgeList.get(j - 1 )+"->");
  90.                      }else
  91.                      {
  92.                          System.out.print(edgeList.get(j - 1 ));
  93.                          break;
  94.                      }						 
  95.                  }
  96.                  System.out.println();					
  97.               }
  98.           } 
  99.           catch(InputMismatchException inputMismatch)
  100.           {
  101.               System.out.println("Error in Input Format. \nFormat : <source index> <destination index>");
  102.           }
  103.           scan.close();
  104.      }
  105. }


$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

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.