Find intersection point of two Linked Lists without finding the length
Last Updated :
10 Apr, 2023
There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y shaped list. Write a program to get the point where both the linked lists merge.
Examples:
Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6
^
|
7 -> 8 -> 9
Output: 4
Input: 13 -> 14 -> 5 -> 6
^
|
10 -> 2 -> 3 -> 4
Output: 14
Prerequisites: Write a function to get the intersection point of two Linked Lists
Approach: Take two pointers for the heads of both the linked lists. If one of them reaches the end earlier then use it by moving it to the beginning of the other list. Once both of them go through reassigning they will be equidistance from the collision point.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
class Node {
public:
int data;
Node* next;
};
// Function to return the intersection point
// of the two linked lists head1 and head2
int getIntesectionNode(Node* head1, Node* head2)
{
Node* current1 = head1;
Node* current2 = head2;
// If one of the head is NULL
if (!current1 or !current2)
return -1;
// Continue until we find intersection node
while (current1 and current2
and current1 != current2) {
current1 = current1->next;
current2 = current2->next;
// If we get intersection node
if (current1 == current2)
return current1->data;
// If one of them reaches end
if (!current1)
current1 = head2;
if (!current2)
current2 = head1;
}
return current1->data;
}
// Driver code
int main()
{
/*
Create two linked lists
1st 3->6->9->15->30
2nd 10->15->30
15 is the intersection point
*/
Node* newNode;
// Addition of new nodes
Node* head1 = new Node();
head1->data = 10;
Node* head2 = new Node();
head2->data = 3;
newNode = new Node();
newNode->data = 6;
head2->next = newNode;
newNode = new Node();
newNode->data = 9;
head2->next->next = newNode;
newNode = new Node();
newNode->data = 15;
head1->next = newNode;
head2->next->next->next = newNode;
newNode = new Node();
newNode->data = 30;
head1->next->next = newNode;
head1->next->next->next = NULL;
cout << getIntesectionNode(head1, head2);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
/* Link list node */
static class Node
{
int data;
Node next;
};
// Function to return the intersection point
// of the two linked lists head1 and head2
static int getIntesectionNode(Node head1, Node head2)
{
Node current1 = head1;
Node current2 = head2;
// If one of the head is null
if (current1 == null || current2 == null )
return -1;
// Continue until we find intersection node
while (current1 != null && current2 != null
&& current1 != current2)
{
current1 = current1.next;
current2 = current2.next;
// If we get intersection node
if (current1 == current2)
return current1.data;
// If one of them reaches end
if (current1 == null )
current1 = head2;
if (current2 == null )
current2 = head1;
}
return current1.data;
}
// Driver code
public static void main(String[] args)
{
/*
Create two linked lists
1st 3.6.9.15.30
2nd 10.15.30
15 is the intersection point
*/
Node newNode;
// Addition of new nodes
Node head1 = new Node();
head1.data = 10;
Node head2 = new Node();
head2.data = 3;
newNode = new Node();
newNode.data = 6;
head2.next = newNode;
newNode = new Node();
newNode.data = 9;
head2.next.next = newNode;
newNode = new Node();
newNode.data = 15;
head1.next = newNode;
head2.next.next.next = newNode;
newNode = new Node();
newNode.data = 30;
head1.next.next = newNode;
head1.next.next.next = null;
System.out.print(getIntesectionNode(head1, head2));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation of the approach
''' Link list node '''
class new_Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
# Function to return the intersection point
# of the two linked lists head1 and head2
def getIntesectionNode(head1, head2):
current1 = head1
current2 = head2
# If one of the head is None
if (not current1 or not current2 ):
return -1
# Continue until we find intersection node
while (current1 and current2 and current1 != current2):
current1 = current1.next
current2 = current2.next
# If we get intersection node
if (current1 == current2):
return current1.data
# If one of them reaches end
if (not current1):
current1 = head2
if (not current2):
current2 = head1
return current1.data
# Driver code
'''
Create two linked lists
1st 3.6.9.15.30
2nd 10.15.30
15 is the intersection po
'''
# Addition of newNodes
head1 = new_Node(10)
head2 = new_Node(3)
newNode = new_Node(6)
head2.next = newNode
newNode = new_Node(9)
head2.next.next = newNode
newNode = new_Node(15)
head1.next = newNode
head2.next.next.next = newNode
newNode = new_Node(30)
head1.next.next = newNode
head1.next.next.next = None
print(getIntesectionNode(head1, head2))
# This code is contributed by shubhamsingh10
C#
// C# implementation of the approach
using System;
class GFG
{
/* Link list node */
class Node
{
public int data;
public Node next;
};
// Function to return the intersection point
// of the two linked lists head1 and head2
static int getIntesectionNode(Node head1, Node head2)
{
Node current1 = head1;
Node current2 = head2;
// If one of the head is null
if (current1 == null || current2 == null )
return -1;
// Continue until we find intersection node
while (current1 != null && current2 != null
&& current1 != current2)
{
current1 = current1.next;
current2 = current2.next;
// If we get intersection node
if (current1 == current2)
return current1.data;
// If one of them reaches end
if (current1 == null )
current1 = head2;
if (current2 == null )
current2 = head1;
}
return current1.data;
}
// Driver code
public static void Main(String[] args)
{
/*
Create two linked lists
1st 3.6.9.15.30
2nd 10.15.30
15 is the intersection point
*/
Node newNode;
// Addition of new nodes
Node head1 = new Node();
head1.data = 10;
Node head2 = new Node();
head2.data = 3;
newNode = new Node();
newNode.data = 6;
head2.next = newNode;
newNode = new Node();
newNode.data = 9;
head2.next.next = newNode;
newNode = new Node();
newNode.data = 15;
head1.next = newNode;
head2.next.next.next = newNode;
newNode = new Node();
newNode.data = 30;
head1.next.next = newNode;
head1.next.next.next = null;
Console.Write(getIntesectionNode(head1, head2));
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// Javascript implementation of the approach
/* Link list node */
class Node {
constructor()
{
this.data = 0;
this.next = null;
}
};
// Function to return the intersection point
// of the two linked lists head1 and head2
function getIntesectionNode(head1, head2)
{
var current1 = head1;
var current2 = head2;
// If one of the head is null
if (!current1 || !current2)
return -1;
// Continue until we find intersection node
while (current1 && current2
&& current1 != current2) {
current1 = current1.next;
current2 = current2.next;
// If we get intersection node
if (current1 == current2)
return current1.data;
// If one of them reaches end
if (!current1)
current1 = head2;
if (!current2)
current2 = head1;
}
return current1.data;
}
// Driver code
/*
Create two linked lists
1st 3.6.9.15.30
2nd 10.15.30
15 is the intersection point
*/
var newNode;
// Addition of new nodes
var head1 = new Node();
head1.data = 10;
var head2 = new Node();
head2.data = 3;
newNode = new Node();
newNode.data = 6;
head2.next = newNode;
newNode = new Node();
newNode.data = 9;
head2.next.next = newNode;
newNode = new Node();
newNode.data = 15;
head1.next = newNode;
head2.next.next.next = newNode;
newNode = new Node();
newNode.data = 30;
head1.next.next = newNode;
head1.next.next.next = null;
document.write( getIntesectionNode(head1, head2));
// This code is contributed by noob2000.
</script>
Time complexity O(m+n),where m and n are the lengths of the two linked lists
Space complexity O(1),as it uses a constant amount of additional memory to store only a few pointers to nodes.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read