×

Intersection Point in Y Shaped Linked Lists in Java

Intersection Point in Y Shaped Linked Lists in Java

In this article, we are going to see how to find the intersection point in a Y-shaped linked list.

Method 1:

We need to find a common node of two linked lists. So we will insert all nodes of the first linked list into the HashSet, and then we will check the second linked list. We can do this using the following steps:

  • Firstly, we will create an empty hash set.
  • Then, we will traverse the entire first linked list and insert all node addresses in the hash set.
  • After this, we will traverse the second linked list and check the node of the second linked list in the HashSet. If we find the common node, we will return that node.

Source code to implement method 1 in Java:

 import java.util.*;
 class Node
 {
     int data;
     Node next;
     Node(int d) {
         data = d;
         next = null;
     }
 }
  class LinkedList_Intersection
 {
            Node head = null; 
             Node tail = null;
 public void addToTheLast(Node node)
 {
   if (head == null) {
    head = node;
    tail = head;
   }
  else {  
    tail.next=node;
    tail = node;
   }
 }
   /* Function to print linked list */
     void printList()
     {
         Node temp = head;
         while (temp != null)
         {
            System.out.print(temp.data+" ");
            temp = temp.next;
         } 
         System.out.println();
     }
      /* Driver program to test above functions */
     public static void main(String args[])
     {
          Scanner sc = new Scanner(System.in);
                                     int n1 = sc.nextInt();
                                     int n2 = sc.nextInt();
                                     int n3 = sc.nextInt();
                                     LinkedList_Intersection llist1 = new LinkedList_Intersection();
                                 LinkedList_Intersection llist2 = new LinkedList_Intersection();
                                     LinkedList_Intersection llist3 = new LinkedList_Intersection();
                                                 int a1=sc.nextInt();
                                                 Node head1= new Node(a1);
                                                 Node tail1= head1;
                                                 for (int i = 1; i < n1; i++)
                                                 {
                                                             int a = sc.nextInt();
                                                             tail1.next = (new Node(a));
                                                             tail1= tail1.next;
                                                 }
                                                 int b1=sc.nextInt();
                                                 Node head2 = new Node(b1);
                                                 Node tail2 = head2;
                                                 for (int i = 1; i < n2; i++)
                                                 {
                                                             int b = sc.nextInt(); 
                                                             tail2.next = (new Node(b));
                                                             tail2= tail2.next;
                                                 }
                                                 int c1=sc.nextInt();
                                                 Node head3= new Node(c1);
                                                 tail1.next = head3;
                                                 tail2.next = head3;
                                                 Node tail3 = head3;
                                                 for (int i = 1; i < n3; i++)
                                                 {
                                                             int c = sc.nextInt();  
                                                             tail3.next = (new Node(c));
                                                             tail3= tail3.next;
                                                 }
                                                 Intersect obj = new Intersect();
                                                 Node temp=obj.intersectPoint(head1, head2);
                                                 if(temp==null)
                                                             System.out.println("No Intersection Found");
                                                 else
                                                             System.out.println("Intersection at-"+temp.data);
     }
 }
 class Intersect
 {
             Node intersectPoint(Node head1, Node head2)
             {
             HashSet<Node> hs = new HashSet<Node>();
             while (head1 != null) {
             hs.add(head1);
             head1 = head1.next;
         }
         while (head2!= null) {
             if (hs.contains(head2)) {
                 return head2;
             }
             head2 = head2.next;
         }
         return null;
     }
 } 

Output: -

Intersection Point in Y Shaped

In this output, the first line contains the total no of nodes in the first linked list. The second line contains the total number of nodes in the second linked list, and the third line contains the total number of nodes in the common linked list. Then, we will insert the elements for these three linked lists, respectively.

Time Complexity: O(N+M)

Auxiliary Space: O(N)

Method 2: Two-pointer Technique:

This method uses two pointers to return the common node with the help of the following steps:

  • Initialize two pointers ptr1 and ptr2, at the head1 and head2.
  • Traverse through the lists, one node at a time.
  • When ptr1 reaches the end of a list, then redirect it to the head2.
  • Similarly, when ptr2 reaches the end of a list, redirect it to the head1.
  • Once both of them go through reassigning, they will be equidistant from the collision point.
  • If at any node ptr1 meets ptr2, then it is the intersection node.
  • After the second iteration, if there is no intersection node, it returns NULL.

Source code to implement method 2 in Java:

 import java.util.*;
 class Node
 {
     int data;
     Node next;
     Node(int d) {
         data = d;
         next = null;
     }
 }
  class LinkedList_Intersection
 {
            Node head = null; 
             Node tail = null;
 public void addToTheLast(Node node)
 {
   if (head == null) {
    head = node;
    tail = head;
   }
  else {  
    tail.next=node;
    tail = node;
   }
 }
   /* Function to print linked list */
     void printList()
     {
         Node temp = head;
         while (temp != null)
         {
            System.out.print(temp.data+" ");
            temp = temp.next;
         } 
         System.out.println();
     }
      /* Driver program to test above functions */
     public static void main(String args[])
     {
          Scanner sc = new Scanner(System.in);
                                     int n1 = sc.nextInt();
                                     int n2 = sc.nextInt();
                                     int n3 = sc.nextInt();
                                     LinkedList_Intersection llist1 = new LinkedList_Intersection();
                                    LinkedList_Intersection llist2 = new LinkedList_Intersection();
                                     LinkedList_Intersection llist3 = new LinkedList_Intersection();
                                                 int a1=sc.nextInt();
                                                 Node head1= new Node(a1);
                                                 Node tail1= head1;
                                                 for (int i = 1; i < n1; i++)
                                                 {
                                                             int a = sc.nextInt();
                                                             tail1.next = (new Node(a));
                                                             tail1= tail1.next;
                                                 }
                                                 int b1=sc.nextInt();
                                                 Node head2 = new Node(b1);
                                                 Node tail2 = head2;
                                                 for (int i = 1; i < n2; i++)
                                                 {
                                                             int b = sc.nextInt(); 
                                                             tail2.next = (new Node(b));
                                                             tail2= tail2.next;
                                                 }
                                                 int c1=sc.nextInt();
                                                 Node head3= new Node(c1);
                                                 tail1.next = head3;
                                                 tail2.next = head3;
                                                 Node tail3 = head3;
                                                 for (int i = 1; i < n3; i++)
                                                 {
                                                             int c = sc.nextInt();  
                                                             tail3.next = (new Node(c));
                                                             tail3= tail3.next;
                                                 }
                                                 Intersect obj = new Intersect();
                                                 Node temp=obj.intersectPoint(head1, head2);
                                                 if(temp==null)
                                                             System.out.println("No Intersection Found");
                                                 else
                                                             System.out.println("Intersection at-"+temp.data);
     }
 }
 class Intersect
 {
             Node intersectPoint(Node head1, Node head2)
             {
                   Node curr1 = head1, curr2 = head2; 
     while (curr1 != curr2) 
     {
         if (curr1 == null)
         {
             curr1 = head2;
         }
         else
         {
             curr1 = curr1.next;
         }
         if (curr2 == null)
         {
             curr2 = head1;
         }
         else
         {
             curr2 = curr2.next;
         }
     }
     return curr1;
 }
 } 

Output: -

Intersection Point in Y Shaped

Time Complexity: O(N+M)

Auxiliary Space: O(1)


Related Topics

Find the nth node from the end of a Linked List

Find the nth node from the end of a Linked List In this problem, we have given a singly linked list and a number 'n,' and we need to find the...

3 minutes read.

Write Main Difference Between Tree and Graph in Data Structures

Graph: The graph has two sets, which are considered V and E. These vertices are also called nodes, and edges are referred to as arcs connecting any two nodes in a...

4 minutes read.

Lowest common ancestor in a binary search tree

Suppose you have given two values of nodes in a binary search tree. You have to find out the lowest common ancestor between the nodes. Let’s take an example tree- For the...

4 minutes read.

Difference between Stack and Queue

In this article, we will learn about the major differences between Stack and Queue data structures. What is a stack? Stack – A stack is an abstract data structure defined as the...

3 minutes read.

Finding the Sum of All Paths in a Binary Tree

Implementation // Writing the C++ program to implement the below approach.  #include <bits/stdc++.h> using namespace std; // creating the new tree node structure. struct Tree__nod { int val; Tree__nod *Lft, *Rt; }; // creating a new function that will...

8 minutes read.

Insertion in B+ Tree

We will learn how to insert a node in the B+ tree and what are the different properties we are going to follow. Except for the root node, every node should...

5 minutes read.

Bubble Sort vs Selection Sort

In this article, we will discuss the basic differences between these two sorting algorithms. Let us have a quick overview of what these sorting algorithms are? And what are the...

6 minutes read.

Asynchronous advantage actor-critic (A3C) Algorithm

The Asynchronous advantage actor-critic (A3C) Algorithm is one of the latest algorithms developed by the Artificial Intelligence division, Deep Mind at Google. It is used for the Deep Reinforcement Learning...

3 minutes read.

Binary tree deletion

This article will discuss the deletion operation's implementation in the binary tree. The deletion operation helps us eliminate an element from the tree. Implementation #include <bits/stdc++.h> using namespace std; /* A binary tree node...

4 minutes read.

What is the Use of Segment Trees in Data Structure?

Segment trees Segment trees are also called statistical trees in computer science. They are a type of tree data structure. Segment trees are used to store information regarding segments and intervals....

6 minutes read.

DFS (Depth-first search) Algorithm: Data Structure

What is DFS (Depth-first search)? The depth first search is a graph traversal algorithm. The idea behind this algorithm is backtracking and it is a kind of recursive algorithm. In the...

3 minutes read.

Primitive Data Structure in C

The data structure is a logical or mathematical model for organizing and structuring the main memory or elements. We can classify the data structures in two ways one is primitive, and...

10 minutes read.

Flatten Binary Tree to a linked list

Implementation In this section, we will see the implementation of the binary Tree and its conversion into linked lists. let us proceed: - // Writing a C++ program that will convert a...

4 minutes read.

Linear Queue Data Structure in C

Data Structure There are many ways to store data in programming, that Queue has features that make it all the more special. We all know that data structure is a way...

9 minutes read.

Left View of Binary Tree

Implementation // creating a C++ program to print the Left view of the binary tree. #include <bits/stdc++.h> using namespace std; struct Nod { int record; struct Nod *Lft, *Rt; }; // creating a utility function that will eventually help...

4 minutes read.

Linked List Data Structure

Linked list in DS: The linked list is a non-primitive and linear data structure. It is a list of a particular type of data element that is connected to each...

3 minutes read.

Heap Sort in Data Structure

Heap Sort A heap is a tree-based data structure that has specific properties. Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.If...

6 minutes read.

What is a Height-Balanced Tree in Data Structure

A height-balanced tree is a type of binary tree. If the absolute difference between the heights of the left and right subtree is less than or equal to 1, then...

6 minutes read.

Given a Binary Tree, Print the Pre-order Traversal in Recursive

Implementation #include <stdio.h> #include <stdlib.h>   /* Creating a binary tree node that consists of some data along with the pointer to the left and right child.  */ struct __nod {     int record;     struct...

4 minutes read.

Time Complexity of Selection Sort in Data Structure

What is Time Complexity? The term “Time complexity” can be defined as the number of times executions made of a particular sequence of instructions and not the total amount of time...

3 minutes read.