| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- // Java Program to Implement the Directed Graph
- // Using Linked List
- // Importing standard classes from respectively packages
- import java.io.*;
- import java.util.*;
- // Main class
- class GFG_direct {
- // Method 1
- // To make pair of nodes
- static void
- addEdge(LinkedList<LinkedList<Integer> > Adj, int u,
- int v)
- {
- // Creating unidirectional vertex
- Adj.get(u).add(v);
- }
- // Method 2
- // To print the adjacency List
- static void
- printadjacencylist(LinkedList<LinkedList<Integer> > adj)
- {
- for (int i = 0; i < adj.size(); ++i) {
- // Printing the head
- if (adj.get(i).size() != 0) {
- System.out.print(i + "->");
- for (int v : adj.get(i)) {
- // Printing the nodes
- System.out.print(v + " ");
- }
- // A new line is needed
- System.out.println();
- }
- }
- }
- // Method 3
- // Main driver method
- public static void main(String[] args)
- {
- // Creating vertex
- int V = 5;
- LinkedList<LinkedList<Integer> > adj
- = new LinkedList<LinkedList<Integer> >();
- for (int i = 0; i < V; ++i) {
- adj.add(new LinkedList<Integer>());
- }
- // Inserting nodes
- // Custom input elements
- addEdge(adj, 0, 1);
- addEdge(adj, 0, 4);
- addEdge(adj, 1, 2);
- // Printing adjacency List
- printadjacencylist(adj);
- }
- }
|