×

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.

Length of longest palindrome in a linked list using O(1) extra space

Length of longest palindrome in a linked list using O(1) extra space In this problem, we need to find the length of the longest palindrome list that is present in given...

2 minutes read.

Rotate a Singly Linked List

Rotate a Singly Linked List This article will explain how we can rotate the singly linked list. Here we have given a singly linked list, and we need to rotate this...

4 minutes read.

Given a Binary Tree Swap Nodes at K Height

Implementation // Writing a C++ program that will help us exchange the nodes.  #include<bits/stdc++.h> using namespace std; // Creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a function that will help...

8 minutes read.

Buffer overflow attack with examples

You have undoubtedly faced the term buffer overflow in your programming journey. Many times it occurs when we try to run a piece of code with user input, but it...

4 minutes read.

Optimal binary search tree in DSA

Implementation // A simple way of the recursive implementation of the optimal search that we will perform on the binary tree.   #include <bits/stdc++.h> using namespace std; // we have to create a basic utility...

8 minutes read.

String Operations in Data Structures

Operations on Strings Reversing the order of words in a sentence Reversing a string is a technique that reverses or alters the order of a given string so that the last character...

9 minutes read.

Strictly binary tree in Data Structures?

What is a strictly Binary Tree in Data Structures? There are various kinds of binary trees that we know exist in data structures, and they all have their purposes. In this...

4 minutes read.

Quick Sort vs Merge Sort

In this article, we will take an overview of Quick Sort and Merge Sort and then discuss the differences between them. What is Quick Sort? Quick Sort – The idea behind the...

7 minutes read.

Top view of binary tree

We know that a binary tree is a kind of tree that helps us organize our tree and that it is a kind of non-linear info structure that at least...

4 minutes read.

What is B tree?

What do you mean by B Tree in Data Structures? In the technological world, a B tree is simply a well-managed and coordinated tree and an integral part of the data...

6 minutes read.

What is a Spanning Tree in Data Structure

Data structures Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system used to store, manage,...

5 minutes read.

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a...

4 minutes read.

Data Structure Infix to Postfix Conversion

Infix to Postfix Conversion The infix expression is easy to read and write by humans. In present time, we use the infix expression in our daily life but the computers are...

4 minutes read.

Diameter of a Binary Tree

Implementation We will now witness the implementation of the diameter of a binary tree. // Creating a recursive and challenging C program that will help us determine the diameter of a binary...

4 minutes read.

Box Stacking Problem

Stacking of boxes depending on their base You have been given n different boxes. These boxes will have different heights, widths, and depths. You have to stack all these boxes in...

4 minutes read.

AVL Tree

AVL Tree AVL Tree is referred to as self-balanced or height-balanced binary search tree where the difference between heights of its left subtree and right subtree (Balance Factor) can't more than...

25 minutes read.

Given a Generate all Structurally Unique Binary Search Trees

Implementation // Creating a C++ program that will help us build all the binary search trees for the keys from 1 to n.  #include <bits/stdc++.h> using namespace std; // creating a structure that will...

8 minutes read.

What are the types of Trees in Data Structure

Data structures Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system used to store, manage,...

6 minutes read.

Balanced Binary Tree

A balanced binary tree is just a random nod-based tree with a rule of keeping its height minimum in size to maintain various operations such as insertions, deletions and several...

3 minutes read.