Intersection point of two Linked Lists
Last Updated :
23 Jul, 2025
Given two singly linked lists that merge into a single Y-shaped list. The two lists initially have distinct paths but eventually converge at a common node, forming a Y-shape, the task is to find and return the node where the two lists merge.
Intersection Point of two Linked Lists
The above diagram shows an example with two linked lists having 15 as intersection point.
[Naive Approach] Using two nested loops - O(m*n) Time and O(1) Space
The problem can be easily solved using 2 nested for loops. The outer loop will be for each node of the 1st list and the inner loop will be for each node of the 2nd list. In the inner loop, check if any of the nodes of the 2nd list is the same as the current node of the first linked list. The first node which is same as the current node is the intersection point.
C++
// C++ program to get intersection point of two linked list
// using two nested loops
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int x) {
data = x;
next = nullptr;
}
};
// function to get the intersection point of two linked
// lists head1 and head2
Node *intersectPoint(Node *head1, Node *head2) {
// Iterate over second list and for each node
// Search it in first list
while (head2 != nullptr) {
Node *temp = head1;
while (temp) {
// If both Nodes are same
if (temp == head2)
return head2;
temp = temp->next;
}
head2 = head2->next;
}
// intersection is not present between the lists
return nullptr;
}
int main() {
// creation of first list: 10 -> 15 -> 30
Node *head1 = new Node(10);
head1->next = new Node(15);
head1->next->next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
Node *head2 = new Node(3);
head2->next = new Node(6);
head2->next->next = new Node(9);
// 15 is the intersection point
head2->next->next->next = head1->next;
Node *intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint == nullptr)
cout << "-1";
else
cout << intersectionPoint->data << endl;
}
C
// C program to get intersection point of two linked lists
// using two nested loops
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int data) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// function to get the intersection point of two linked
// lists head1 and head2
struct Node* intersectPoint(struct Node* head1, struct Node* head2) {
// Iterate over second list and for each node
// Search it in first list
while (head2 != NULL) {
struct Node* temp = head1;
while (temp != NULL) {
// If both Nodes are same
if (temp == head2)
return head2;
temp = temp->next;
}
head2 = head2->next;
}
// intersection is not present between the lists
return NULL;
}
int main() {
// creation of first list: 10 -> 15 -> 30
struct Node* head1 = createNode(10);
head1->next = createNode(15);
head1->next->next = createNode(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
struct Node* head2 = createNode(3);
head2->next = createNode(6);
head2->next->next = createNode(9);
// 15 is the intersection point
head2->next->next->next = head1->next;
struct Node* intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint == NULL)
printf("-1\n");
else
printf("%d\n", intersectionPoint->data);
return 0;
}
Java
// Java program to get intersection point of two linked lists
// using two nested loops
class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
}
class GfG {
// function to get the intersection point of two linked
// lists head1 and head2
static Node intersectPoint(Node head1, Node head2) {
// Iterate over second list and for each node
// Search it in first list
while (head2 != null) {
Node temp = head1;
while (temp != null) {
// If both Nodes are same
if (temp == head2)
return head2;
temp = temp.next;
}
head2 = head2.next;
}
// intersection is not present between the lists
return null;
}
public static void main(String[] args) {
// creation of first list: 10 -> 15 -> 30
Node head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
Node head2 = new Node(3);
head2.next = new Node(6);
head2.next.next = new Node(9);
// 15 is the intersection point
head2.next.next.next = head1.next;
Node intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint == null)
System.out.println("-1");
else
System.out.println(intersectionPoint.data);
}
}
Python
# Python program to get intersection point of two linked lists
# using two nested loops
class Node:
def __init__(self, x):
self.data = x
self.next = None
# function to get the intersection point of two linked
# lists head1 and head2
def intersectPoint(head1, head2):
# Iterate over second list and for each node
# Search it in first list
while head2 is not None:
temp = head1
while temp is not None:
# If both Nodes are same
if temp == head2:
return head2
temp = temp.next
head2 = head2.next
# intersection is not present between the lists
return None
if __name__ == "__main__":
# creation of first list: 10 -> 15 -> 30
head1 = Node(10)
head1.next = Node(15)
head1.next.next = Node(30)
# creation of second list: 3 -> 6 -> 9 -> 15 -> 30
head2 = Node(3)
head2.next = Node(6)
head2.next.next = Node(9)
# 15 is the intersection point
head2.next.next.next = head1.next
intersectionPoint = intersectPoint(head1, head2)
if intersectionPoint is None:
print("-1")
else:
print(intersectionPoint.data)
C#
// C# program to get intersection point of two linked lists
// using two nested loops
using System;
class Node {
public int data;
public Node next;
public Node(int x) {
data = x;
next = null;
}
}
class GfG {
// function to get the intersection point of two linked
// lists head1 and head2
static Node intersectPoint(Node head1, Node head2) {
// Iterate over second list and for each node
// Search it in first list
while (head2 != null) {
Node temp = head1;
while (temp != null) {
// If both Nodes are same
if (temp == head2)
return head2;
temp = temp.next;
}
head2 = head2.next;
}
// intersection is not present between the lists
return null;
}
static void Main(string[] args) {
// creation of first list: 10 -> 15 -> 30
Node head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
Node head2 = new Node(3);
head2.next = new Node(6);
head2.next.next = new Node(9);
// 15 is the intersection point
head2.next.next.next = head1.next;
Node intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint == null)
Console.WriteLine("-1");
else
Console.WriteLine(intersectionPoint.data);
}
}
JavaScript
// JavaScript program to get intersection point of two linked lists
// using two nested loops
class Node {
constructor(x) {
this.data = x;
this.next = null;
}
}
// function to get the intersection point of two linked
// lists head1 and head2
function intersectPoint(head1, head2) {
// Iterate over second list and for each node
// Search it in first list
while (head2 !== null) {
let temp = head1;
while (temp !== null) {
// If both Nodes are same
if (temp === head2)
return head2;
temp = temp.next;
}
head2 = head2.next;
}
// Intersection is not present between the lists
return null;
}
// Driver Code
// creation of first list: 10 -> 15 -> 30
let head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
let head2 = new Node(3);
head2.next = new Node(6);
head2.next.next = new Node(9);
// 15 is the intersection point
head2.next.next.next = head1.next;
const intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint === null)
console.log("-1");
else
console.log(intersectionPoint.data);
[Better Approach] Using Hashing - O(m + n) Time and O(m) Space
The idea is to use hashing to store all the nodes of the first list in a hash set and then iterate over second list checking if the node is present in the set. If we find a node which is present in the hash set, we return the node.
C++
// C++ program to get intersection point of two linked
// list using hashing
#include <iostream>
#include <unordered_set>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int x) {
data = x;
next = nullptr;
}
};
// Function to get the intersection point of two linked lists
Node *intersectPoint(Node *head1, Node *head2) {
unordered_set<Node *> visitedNodes;
// Traverse the first list and store all nodes in a set
Node *curr1 = head1;
while (curr1 != nullptr) {
visitedNodes.insert(curr1);
curr1 = curr1->next;
}
// Traverse the second list and check if any node is in the set
Node *curr2 = head2;
while (curr2 != nullptr) {
if (visitedNodes.find(curr2) != visitedNodes.end()) {
// Intersection point found
return curr2;
}
curr2 = curr2->next;
}
return nullptr;
}
int main() {
// creation of first list: 10 -> 15 -> 30
Node *head1 = new Node(10);
head1->next = new Node(15);
head1->next->next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
Node *head2 = new Node(3);
head2->next = new Node(6);
head2->next->next = new Node(9);
// 15 is the intersection point
head2->next->next->next = head1->next;
Node *intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint == nullptr)
cout << "-1";
else
cout << intersectionPoint->data << endl;
}
Java
// Java program to get intersection point of two linked
// list using hashing
import java.util.HashSet;
class Node {
int data;
Node next;
Node(int new_data) {
data = new_data;
next = null;
}
}
class GfG {
// Function to get the intersection point of two linked lists
static Node intersectPoint(Node head1, Node head2) {
HashSet<Node> visitedNodes = new HashSet<>();
// Traverse the first list and store all nodes in a set
Node curr1 = head1;
while (curr1 != null) {
visitedNodes.add(curr1);
curr1 = curr1.next;
}
// Traverse the second list and check if any node is
// in the set
Node curr2 = head2;
while (curr2 != null) {
if (visitedNodes.contains(curr2)) {
// Intersection point found
return curr2;
}
curr2 = curr2.next;
}
return null;
}
public static void main(String[] args) {
// creation of first list: 10 -> 15 -> 30
Node head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
Node head2 = new Node(3);
head2.next = new Node(6);
head2.next.next = new Node(9);
// 15 is the intersection point
head2.next.next.next = head1.next;
Node intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint == null)
System.out.println("-1");
else
System.out.println(intersectionPoint.data);
}
}
Python
# Pyhton program to get intersection point of two linked
# list using hashing
class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
# Function to get the intersection point of two linked lists
def intersectPoint(head1, head2):
visited_nodes = set()
# Traverse the first list and store all nodes in a set
curr1 = head1
while curr1 is not None:
visited_nodes.add(curr1)
curr1 = curr1.next
# Traverse the second list and check if any node is in the set
curr2 = head2
while curr2 is not None:
if curr2 in visited_nodes:
return curr2 # Intersection point found
curr2 = curr2.next
return None
if __name__ == "__main__":
# creation of first list: 10 -> 15 -> 30
head1 = Node(10)
head1.next = Node(15)
head1.next.next = Node(30)
# creation of second list: 3 -> 6 -> 9 -> 15 -> 30
head2 = Node(3)
head2.next = Node(6)
head2.next.next = Node(9)
# 15 is the intersection point
head2.next.next.next = head1.next
intersectionPoint = intersectPoint(head1, head2)
if intersectionPoint is None:
print("-1")
else:
print(intersectionPoint.data)
C#
// C# program to get intersection point of two linked
// list using hashing
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node next;
public Node(int new_data) {
data = new_data;
next = null;
}
}
class GfG {
// Function to get the intersection point of two linked
// lists
static Node intersectPoint(Node head1,
Node head2) {
HashSet<Node> visitedNodes = new HashSet<Node>();
// Traverse the first list and store all nodes in a set
Node curr1 = head1;
while (curr1 != null) {
visitedNodes.Add(curr1);
curr1 = curr1.next;
}
// Traverse the second list and check if any node is
// in the set
Node curr2 = head2;
while (curr2 != null) {
// Intersection point found
if (visitedNodes.Contains(curr2))
return curr2;
curr2 = curr2.next;
}
return null;
}
static void Main(string[] args) {
// creation of first list: 10 -> 15 -> 30
Node head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
Node head2 = new Node(3);
head2.next = new Node(6);
head2.next.next = new Node(9);
// 15 is the intersection point
head2.next.next.next = head1.next;
Node intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint == null)
Console.WriteLine("-1");
else
Console.WriteLine(intersectionPoint.data);
}
}
JavaScript
// Javascipt program to get intersection point of two linked
// list using hashing
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to get the intersection point of two linked
// lists
function intersectPoint(head1, head2) {
const visitedNodes = new Set();
// Traverse the first list and store all nodes in a set
let curr1 = head1;
while (curr1 !== null) {
visitedNodes.add(curr1);
curr1 = curr1.next;
}
// Traverse the second list and check if any node is in
// the set
let curr2 = head2;
while (curr2 !== null) {
if (visitedNodes.has(curr2)) {
return curr2; // Intersection point found
}
curr2 = curr2.next;
}
return null;
}
// Driver Code
// creation of first list: 10 -> 15 -> 30
let head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
let head2 = new Node(3);
head2.next = new Node(6);
head2.next.next = new Node(9);
// 15 is the intersection point
head2.next.next.next = head1.next;
const intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint === null)
console.log("-1");
else
console.log(intersectionPoint.data);
[Expected Approach - 1] Using difference in node counts - O(m + n) Time and O(1) Space
The idea is to find the difference (d) between the count of nodes in both the lists. Initialize the start pointer in both the lists and then increment the start pointer of the longer list by d nodes. Now, we have both start pointers at the same distance from the intersection point, so we can keep incrementing both the start pointers until we find the intersection point.
C++
// C++ program to get intersection point of two linked list
// using count of nodes
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int x) {
data = x;
next = nullptr;
}
};
// Function to get the count of nodes in a linked list
int getCount(Node *head) {
int cnt = 0;
Node *curr = head;
while (curr != nullptr) {
cnt++;
curr = curr->next;
}
return cnt;
}
// Function to get the intersection point of two
// linked lists where head1 has d more nodes than head2
Node* getIntersectionByDiff(int diff, Node *head1, Node *head2) {
Node *curr1 = head1;
Node *curr2 = head2;
// Move the pointer forward by d nodes
for (int i = 0; i < diff; i++) {
if (curr1 == nullptr)
return nullptr;
curr1 = curr1->next;
}
// Move both pointers until they intersect
while (curr1 != nullptr && curr2 != nullptr) {
if (curr1 == curr2)
return curr1;
curr1 = curr1->next;
curr2 = curr2->next;
}
return nullptr;
}
// Function to get the intersection point of two linked lists
Node* intersectPoint(Node *head1, Node *head2) {
// Count the number of nodes in both linked lists
int len1 = getCount(head1);
int len2 = getCount(head2);
int diff = 0;
// If the first list is longer
if (len1 > len2) {
diff = len1 - len2;
return getIntersectionByDiff(diff, head1, head2);
}
else {
diff = len2 - len1;
return getIntersectionByDiff(diff, head2, head1);
}
}
int main() {
// creation of first list: 10 -> 15 -> 30
Node *head1 = new Node(10);
head1->next = new Node(15);
head1->next->next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
Node *head2 = new Node(3);
head2->next = new Node(6);
head2->next->next = new Node(9);
// 15 is the intersection point
head2->next->next->next = head1->next;
Node *intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint == nullptr)
cout << "-1";
else
cout << intersectionPoint->data << endl;
}
C
// C program to get intersection point of two linked list
// using count of nodes
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int data) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to get the count of nodes in a linked list
int getCount(struct Node* head) {
int cnt = 0;
struct Node* curr = head;
while (curr != NULL) {
cnt++;
curr = curr->next;
}
return cnt;
}
// Function to get the intersection point of two
// linked lists where head1 has d more nodes than head2
struct Node* getIntersectionByDiff(int diff, struct Node* head1, struct Node* head2) {
struct Node* curr1 = head1;
struct Node* curr2 = head2;
// Move the pointer forward by d nodes
for (int i = 0; i < diff; i++) {
if (curr1 == NULL)
return NULL;
curr1 = curr1->next;
}
// Move both pointers until they intersect
while (curr1 != NULL && curr2 != NULL) {
if (curr1 == curr2)
return curr1;
curr1 = curr1->next;
curr2 = curr2->next;
}
return NULL;
}
// Function to get the intersection point of two linked lists
struct Node* intersectPoint(struct Node* head1, struct Node* head2) {
// Count the number of nodes in both linked lists
int len1 = getCount(head1);
int len2 = getCount(head2);
int diff = 0;
// If the first list is longer
if (len1 > len2) {
diff = len1 - len2;
return getIntersectionByDiff(diff, head1, head2);
} else {
diff = len2 - len1;
return getIntersectionByDiff(diff, head2, head1);
}
}
int main() {
// creation of first list: 10 -> 15 -> 30
struct Node* head1 = createNode(10);
head1->next = createNode(15);
head1->next->next = createNode(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
struct Node* head2 = createNode(3);
head2->next = createNode(6);
head2->next->next = createNode(9);
// 15 is the intersection point
head2->next->next->next = head1->next;
struct Node* intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint == NULL)
printf("-1\n");
else
printf("%d\n", intersectionPoint->data);
return 0;
}
Java
// Java program to get intersection point of two linked list
// using count of nodes
class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
}
class GfG {
// Function to get the count of nodes in a linked list
static int getCount(Node head) {
int cnt = 0;
Node curr = head;
while (curr != null) {
cnt++;
curr = curr.next;
}
return cnt;
}
// Function to get the intersection point of two
// linked lists where head1 has d more nodes than head2
static Node getIntersectionByDiff(int diff, Node head1, Node head2) {
Node curr1 = head1;
Node curr2 = head2;
// Move the pointer forward by d nodes
for (int i = 0; i < diff; i++) {
if (curr1 == null)
return null;
curr1 = curr1.next;
}
// Move both pointers until they intersect
while (curr1 != null && curr2 != null) {
if (curr1 == curr2)
return curr1;
curr1 = curr1.next;
curr2 = curr2.next;
}
return null;
}
// Function to get the intersection point of two linked lists
static Node intersectPoint(Node head1, Node head2) {
// Count the number of nodes in both linked lists
int len1 = getCount(head1);
int len2 = getCount(head2);
int diff = 0;
// If the first list is longer
if (len1 > len2) {
diff = len1 - len2;
return getIntersectionByDiff(diff, head1, head2);
} else {
diff = len2 - len1;
return getIntersectionByDiff(diff, head2, head1);
}
}
public static void main(String[] args) {
// creation of first list: 10 -> 15 -> 30
Node head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
Node head2 = new Node(3);
head2.next = new Node(6);
head2.next.next = new Node(9);
// 15 is the intersection point
head2.next.next.next = head1.next;
Node intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint == null)
System.out.println("-1");
else
System.out.println(intersectionPoint.data);
}
}
Python
# Python program to get intersection point of two linked list
# using count of nodes
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to get the count of nodes in a linked list
def getCount(head):
cnt = 0
curr = head
while curr:
cnt += 1
curr = curr.next
return cnt
# Function to get the intersection point of two
# linked lists where head1 has d more nodes than head2
def getIntersectionByDiff(diff, head1, head2):
curr1 = head1
curr2 = head2
# Move the pointer forward by d nodes
for _ in range(diff):
if not curr1:
return None
curr1 = curr1.next
# Move both pointers until they intersect
while curr1 and curr2:
if curr1 == curr2:
return curr1
curr1 = curr1.next
curr2 = curr2.next
return None
# Function to get the intersection point of two linked lists
def intersectPoint(head1, head2):
# Count the number of nodes in both linked lists
len1 = getCount(head1)
len2 = getCount(head2)
diff = 0
# If the first list is longer
if len1 > len2:
diff = len1 - len2
return getIntersectionByDiff(diff, head1, head2)
else:
diff = len2 - len1
return getIntersectionByDiff(diff, head2, head1)
if __name__ == "__main__":
# creation of first list: 10 -> 15 -> 30
head1 = Node(10)
head1.next = Node(15)
head1.next.next = Node(30)
# creation of second list: 3 -> 6 -> 9 -> 15 -> 30
head2 = Node(3)
head2.next = Node(6)
head2.next.next = Node(9)
# 15 is the intersection point
head2.next.next.next = head1.next
intersectionPoint = intersectPoint(head1, head2)
if not intersectionPoint:
print("-1")
else:
print(intersectionPoint.data)
C#
// C# program to get intersection point of two linked list
// using count of nodes
using System;
class Node {
public int data;
public Node next;
public Node(int x) {
data = x;
next = null;
}
}
class GfG {
// Function to get the count of nodes in a linked list
static int getCount(Node head) {
int cnt = 0;
Node curr = head;
while (curr != null) {
cnt++;
curr = curr.next;
}
return cnt;
}
// Function to get the intersection point of two
// linked lists where head1 has d more nodes than head2
static Node getIntersectionByDiff(int diff, Node head1, Node head2) {
Node curr1 = head1;
Node curr2 = head2;
// Move the pointer forward by d nodes
for (int i = 0; i < diff; i++) {
if (curr1 == null)
return null;
curr1 = curr1.next;
}
// Move both pointers until they intersect
while (curr1 != null && curr2 != null) {
if (curr1 == curr2)
return curr1;
curr1 = curr1.next;
curr2 = curr2.next;
}
return null;
}
// Function to get the intersection point of two linked lists
static Node intersectPoint(Node head1, Node head2) {
// Count the number of nodes in both linked lists
int len1 = getCount(head1);
int len2 = getCount(head2);
int diff = 0;
// If the first list is longer
if (len1 > len2) {
diff = len1 - len2;
return getIntersectionByDiff(diff, head1, head2);
} else {
diff = len2 - len1;
return getIntersectionByDiff(diff, head2, head1);
}
}
static void Main(string[] args) {
// creation of first list: 10 -> 15 -> 30
Node head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
Node head2 = new Node(3);
head2.next = new Node(6);
head2.next.next = new Node(9);
// 15 is the intersection point
head2.next.next.next = head1.next;
Node intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint == null)
Console.WriteLine("-1");
else
Console.WriteLine(intersectionPoint.data);
}
}
JavaScript
// JavaScript program to get intersection point of two linked list
// using count of nodes
class Node {
constructor(x) {
this.data = x;
this.next = null;
}
}
// Function to get the count of nodes in a linked list
function getCount(head) {
let cnt = 0;
let curr = head;
while (curr !== null) {
cnt++;
curr = curr.next;
}
return cnt;
}
// Function to get the intersection point of two
// linked lists where head1 has d more nodes than head2
function getIntersectionByDiff(diff, head1, head2) {
let curr1 = head1;
let curr2 = head2;
// Move the pointer forward by d nodes
for (let i = 0; i < diff; i++) {
if (curr1 === null)
return null;
curr1 = curr1.next;
}
// Move both pointers until they intersect
while (curr1 !== null && curr2 !== null) {
if (curr1 === curr2)
return curr1;
curr1 = curr1.next;
curr2 = curr2.next;
}
return null;
}
// Function to get the intersection point of two linked lists
function intersectPoint(head1, head2) {
// Count the number of nodes in both linked lists
let len1 = getCount(head1);
let len2 = getCount(head2);
let diff = 0;
// If the first list is longer
if (len1 > len2) {
diff = len1 - len2;
return getIntersectionByDiff(diff, head1, head2);
} else {
diff = len2 - len1;
return getIntersectionByDiff(diff, head2, head1);
}
}
// Driver Code
// creation of first list: 10 -> 15 -> 30
let head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
let head2 = new Node(3);
head2.next = new Node(6);
head2.next.next = new Node(9);
// 15 is the intersection point
head2.next.next.next = head1.next;
let intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint === null)
console.log("-1");
else
console.log(intersectionPoint.data);
[Expected Approach - 2] Using Two Pointer Technique - O(m + n) Time and O(1) Space
The idea is to traverse the two given linked lists simultaneously, using two pointers. When one pointer reaches the end of its list, it is reassigned to the head of the other list. This process continues until the two pointers meet, which indicates that they have reached the intersection point.
Follow the steps below to solve the problem:
- Initialize two pointers ptr1 and ptr2 at head1 and head2 respectively.
- Traverse through the lists, one node at a time.
- When ptr1 reaches the end of a list, then redirect it to 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 at equal distance 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 , returns NULL.
C++
// C++ program to find the intersection point of two
// linked lists using Two Pointers Technique
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int x) {
data = x;
next = nullptr;
}
};
// Function to get the intersection point of two linked lists
Node *intersectPoint(Node *head1, Node *head2) {
// Maintaining two pointers ptr1 and ptr2
// at the heads of the lists
Node *ptr1 = head1;
Node *ptr2 = head2;
// If any one of the heads is NULL, there is no intersection
if (ptr1 == nullptr || ptr2 == nullptr)
return nullptr;
// Traverse through the lists until both pointers meet
while (ptr1 != ptr2) {
// Move to the next node in each list and if the one
// pointer reaches NULL, start from the other linked list
ptr1 = ptr1 ? ptr1->next : head2;
ptr2 = ptr2 ? ptr2->next : head1;
}
// Return the intersection node, or nullptr if no intersection
return ptr1;
}
int main() {
// creation of first list: 10 -> 15 -> 30
Node *head1 = new Node(10);
head1->next = new Node(15);
head1->next->next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
Node *head2 = new Node(3);
head2->next = new Node(6);
head2->next->next = new Node(9);
// 15 is the intersection point
head2->next->next->next = head1->next;
Node *intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint == nullptr)
cout << "-1";
else
cout << intersectionPoint->data << endl;
}
C
// C program to find the intersection point of two
// linked lists using Two Pointers Technique
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to get the intersection point of two linked lists
struct Node* intersectPoint(struct Node* head1, struct Node* head2) {
// Maintaining two pointers ptr1 and ptr2
// at the heads of the lists
struct Node* ptr1 = head1;
struct Node* ptr2 = head2;
// If any one of the heads is NULL, there is no intersection
if (ptr1 == NULL || ptr2 == NULL)
return NULL;
// Traverse through the lists until both pointers meet
while (ptr1 != ptr2) {
// Move to the next node in each list and if the one
// pointer reaches NULL, start from the other linked list
ptr1 = ptr1 ? ptr1->next : head2;
ptr2 = ptr2 ? ptr2->next : head1;
}
// Return the intersection node, or NULL if no intersection
return ptr1;
}
int main() {
// creation of first list: 10 -> 15 -> 30
struct Node* head1 = createNode(10);
head1->next = createNode(15);
head1->next->next = createNode(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
struct Node* head2 = createNode(3);
head2->next = createNode(6);
head2->next->next = createNode(9);
// 15 is the intersection point
head2->next->next->next = head1->next;
struct Node* intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint == NULL)
printf("-1\n");
else
printf("%d\n", intersectionPoint->data);
return 0;
}
Java
// Java program to find the intersection point of two
// linked lists using Two Pointers Technique
class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
}
class GfG {
// Function to get the intersection point of two linked lists
static Node intersectPoint(Node head1, Node head2) {
// Maintaining two pointers ptr1 and ptr2
// at the heads of the lists
Node ptr1 = head1;
Node ptr2 = head2;
// If any one of the heads is NULL, there is no intersection
if (ptr1 == null || ptr2 == null)
return null;
// Traverse through the lists until both pointers meet
while (ptr1 != ptr2) {
// Move to the next node in each list and if the one
// pointer reaches NULL, start from the other linked list
ptr1 = (ptr1 != null) ? ptr1.next : head2;
ptr2 = (ptr2 != null) ? ptr2.next : head1;
}
// Return the intersection node, or null if no intersection
return ptr1;
}
public static void main(String[] args) {
// creation of first list: 10 -> 15 -> 30
Node head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
Node head2 = new Node(3);
head2.next = new Node(6);
head2.next.next = new Node(9);
// 15 is the intersection point
head2.next.next.next = head1.next;
Node intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint == null)
System.out.println("-1");
else
System.out.println(intersectionPoint.data);
}
}
Python
# Python program to find the intersection point of two
# linked lists using Two Pointers Technique
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to get the intersection point of two linked lists
def intersectPoint(head1, head2):
# Maintaining two pointers ptr1 and ptr2
# at the heads of the lists
ptr1 = head1
ptr2 = head2
# If any one of the heads is None, there is no intersection
if not ptr1 or not ptr2:
return None
# Traverse through the lists until both pointers meet
while ptr1 != ptr2:
# Move to the next node in each list and if the one
# pointer reaches None, start from the other linked list
ptr1 = ptr1.next if ptr1 else head2
ptr2 = ptr2.next if ptr2 else head1
# Return the intersection node, or None if no intersection
return ptr1
if __name__ == "__main__":
# creation of first list: 10 -> 15 -> 30
head1 = Node(10)
head1.next = Node(15)
head1.next.next = Node(30)
# creation of second list: 3 -> 6 -> 9 -> 15 -> 30
head2 = Node(3)
head2.next = Node(6)
head2.next.next = Node(9)
# 15 is the intersection point
head2.next.next.next = head1.next
intersectionPoint = intersectPoint(head1, head2)
if not intersectionPoint:
print("-1")
else:
print(intersectionPoint.data)
C#
// C# program to find the intersection point of two
// linked lists using Two Pointers Technique
using System;
class Node {
public int data;
public Node next;
public Node(int x) {
data = x;
next = null;
}
}
class GfG {
// Function to get the intersection point of two linked lists
static Node intersectPoint(Node head1, Node head2) {
// Maintaining two pointers ptr1 and ptr2
// at the heads of the lists
Node ptr1 = head1;
Node ptr2 = head2;
// If any one of the heads is null, there is no intersection
if (ptr1 == null || ptr2 == null)
return null;
// Traverse through the lists until both pointers meet
while (ptr1 != ptr2) {
// Move to the next node in each list and if the one
// pointer reaches null, start from the other linked list
ptr1 = (ptr1 != null) ? ptr1.next : head2;
ptr2 = (ptr2 != null) ? ptr2.next : head1;
}
// Return the intersection node, or null if no intersection
return ptr1;
}
public static void Main(string[] args) {
// creation of first list: 10 -> 15 -> 30
Node head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
Node head2 = new Node(3);
head2.next = new Node(6);
head2.next.next = new Node(9);
// 15 is the intersection point
head2.next.next.next = head1.next;
Node intersectionPoint = intersectPoint(head1, head2);
if (intersectionPoint == null)
Console.WriteLine("-1");
else
Console.WriteLine(intersectionPoint.data);
}
}
JavaScript
// JavaScript program to find the intersection point of two
// linked lists using Two Pointers Technique
class Node {
constructor(x) {
this.data = x;
this.next = null;
}
}
// Function to get the intersection point of two linked lists
function intersectPoint(head1, head2) {
// Maintaining two pointers ptr1 and ptr2
// at the heads of the lists
let ptr1 = head1;
let ptr2 = head2;
// If any one of the heads is null, there is no intersection
if (!ptr1 || !ptr2) return null;
// Traverse through the lists until both pointers meet
while (ptr1 !== ptr2) {
// Move to the next node in each list and if the one
// pointer reaches null, start from the other linked list
ptr1 = ptr1 ? ptr1.next : head2;
ptr2 = ptr2 ? ptr2.next : head1;
}
// Return the intersection node, or null if no intersection
return ptr1;
}
// Driver Code
// creation of first list: 10 -> 15 -> 30
let head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(30);
// creation of second list: 3 -> 6 -> 9 -> 15 -> 30
let head2 = new Node(3);
head2.next = new Node(6);
head2.next.next = new Node(9);
// 15 is the intersection point
head2.next.next.next = head1.next;
let intersectionPoint = intersectPoint(head1, head2);
if (!intersectionPoint) console.log("-1");
else console.log(intersectionPoint.data);
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem