×

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

Introduction to Arrays

What exactly is an array? A group of related data pieces stored in contiguous memory regions is referred to as an array. It is the most basic data structure in which...

5 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.

Adding one to the number represented an array of digits

You have given one array, which consists of values which represent the different digits of a number. You have to add 1 to this number and store the result in...

3 minutes read.

What is a Tree in Terms of a Graph?

To know the explanation of trees in terms of graphs, we need first to know what trees and graphs are. So let us first learn about trees and graphs. Trees and...

6 minutes read.

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.

Bookshop management system using file handling in C++

We see different software in every hospitals or library to manage their database. It is very important to store organization’s data. So we use this software. Now we are going...

5 minutes read.

Semi-Structured data

In this article, we will discuss the semi-structured data. Data can be defined as the distinct piece of information that is gathered and translated for some purpose. It can be...

5 minutes read.

Circular Queue

Circular Queue Circular Queue is special type queue, which follows First in First Out (FIFO) rule and as well as instead of ending queue at the last position, it starts again...

4 minutes read.

Array Data Structure

Data Structure Array: The array is a non-primitive and linear data structure that is a group of similar data items. That is, it can store only one type of data....

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.

Types of Data Structures

Almost every programme or software system that has been built makes use of data structures. Furthermore, data structures are basics of computer science and software engineering. When it comes to...

7 minutes read.

Compare Balanced Binary Tree and Complete Binary Tree

Complete and balanced binary trees are important and general topics in the concept – Tree data structure. Before discussing the complete and balanced binary tree, we need to have an...

8 minutes read.

B Tree vs B + Tree: Data Structure

Difference Between B Tree and B+ Tree What is B Tree? B-Tree is a self-balancing or special type of m-way tree. B-Trees are used mainly in disc access. If we want...

3 minutes read.

Stack vs Array

Difference between Array and Stack In this article, we are going to discuss the major differences between the stack and array data structures: Array – In the data structure, the array is...

3 minutes read.

Binary Tree vs Binary Search Tree: Data Structure

Difference Between Binary Tree and Binary Search Tree What is Binary Tree? A tree which each node can have utmost two children called binary tree. These children are referred as the ‘left...

3 minutes read.

Linear Search

Searching: In the data structure, searching is the process in which an element is searched in a list that satisfies one or more than one condition. Types of searching There are two...

4 minutes read.

Symmetric binary tree

Implementation // writing a C++ program to check whether a given binary tree is symmetric or not. #include <bits/stdc++.h> using namespace std; // creating a binary tree node. struct __Nod { int ky; struct __Nod *Lft, *Rt; }; //...

4 minutes read.

Heap Sort in Data Structure

Heap Sort: Heap Sort is very useful and efficient sorting algorithm in data structure. We can say it is a comparison base sorting algorithm, similar sort where we will find...

2 minutes read.

Singly Linked list

Singly Linked list A singly linked list is a kind of linked list which is unidirectional. If we talk about singly linked list, then we can say it can be traversed...

3 minutes read.

Stack vs Queue: Data Structure

 Difference Between Stack and Queue What is Stack? The LIFO principle applies on insertion and deletion operations of the stack which means last inserted element to the stack will remove first....

3 minutes read.