GFG.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Java Program to Implement the Unidirectional Graph
  2. // Using Linked List
  3. // Importing required classes from packages
  4. import java.io.*;
  5. import java.util.*;
  6. // Main class
  7. class GFG {
  8. // Method 1
  9. // To make pair of nodes
  10. static void
  11. addEdge(LinkedList<LinkedList<Integer> > Adj, int u,
  12. int v)
  13. {
  14. // Creating bi-directional vertex
  15. Adj.get(u).add(v);
  16. Adj.get(v).add(u);
  17. }
  18. // Method 2
  19. // To print the adjacency list
  20. static void
  21. printadjacencylist(LinkedList<LinkedList<Integer> > adj)
  22. {
  23. for (int i = 0; i < adj.size(); ++i) {
  24. // Printing the head
  25. System.out.print(i + "->");
  26. for (int v : adj.get(i)) {
  27. // Printing the nodes
  28. System.out.print(v + " ");
  29. }
  30. // Now a new line is needed
  31. System.out.println();
  32. }
  33. }
  34. // Method 3
  35. // Main driver method
  36. public static void main(String[] args)
  37. {
  38. // Creating vertex
  39. int V = 5;
  40. LinkedList<LinkedList<Integer> > adj
  41. = new LinkedList<LinkedList<Integer> >();
  42. for (int i = 0; i < V; ++i) {
  43. adj.add(new LinkedList<Integer>());
  44. }
  45. // Inserting nodes
  46. // Custom input node elements
  47. addEdge(adj, 0, 1);
  48. addEdge(adj, 0, 4);
  49. addEdge(adj, 1, 2);
  50. addEdge(adj, 1, 3);
  51. addEdge(adj, 1, 4);
  52. addEdge(adj, 2, 3);
  53. addEdge(adj, 3, 4);
  54. // Printing adjacency list
  55. printadjacencylist(adj);
  56. }
  57. }