Find the common nodes in two singly linked list
Given two linked list, the task is to find the number of common nodes in both singly linked list.
Examples:
Input: List A = 3 -> 4 -> 12 -> 10 -> 17, List B = 10 -> 4 -> 8 -> 575 -> 34 -> 12
Output: Number of common nodes in both list is = 3
Input: List A = 12 -> 4 -> 65 -> 14 -> 59, List B = 14 -> 15 -> 23 -> 17 -> 41 -> 54
Output: Number of common nodes in both list is = 1
Naive Approach: Compare every node of list A with every node of list B. If the node is a match then increment the count and return count after all the nodes get compared.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
int countCommonNodes( struct Node* head1, struct Node* head2)
{
struct Node* current1 = head1;
struct Node* current2 = head2;
int count = 0;
while (current1 != NULL) {
while (current2 != NULL) {
if (current1->data == current2->data)
count++;
current2 = current2->next;
}
current1 = current1->next;
current2 = head2;
}
return count;
}
void push( struct Node** head_ref, int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
void printList( struct Node* head)
{
while (head != NULL) {
cout << head->data << " " ;
head = head->next;
}
cout << endl;
}
int main()
{
struct Node* head1 = NULL;
struct Node* head2 = NULL;
push(&head1, 17);
push(&head1, 10);
push(&head1, 12);
push(&head1, 4);
push(&head1, 3);
push(&head2, 12);
push(&head2, 34);
push(&head2, 575);
push(&head2, 8);
push(&head2, 4);
push(&head2, 10);
cout << "Given Linked List A: \n" ;
printList(head1);
cout << "Given Linked List B: \n" ;
printList(head2);
int count = countCommonNodes(head1, head2);
cout << "Number of common node in both list is = " << count;
return 0;
}
|
Java
class GFG {
static class Node {
int data;
Node next;
};
static int countCommonNodes(Node head1, Node head2)
{
Node current1 = head1;
Node current2 = head2;
int count = 0 ;
while (current1 != null ) {
while (current2 != null ) {
if (current1.data == current2.data)
count++;
current2 = current2.next;
}
current1 = current1.next;
current2 = head2;
}
return count;
}
static Node push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
static void printList(Node head)
{
while (head != null ) {
System.out.print(head.data + " " );
head = head.next;
}
System.out.println();
}
public static void main(String args[])
{
Node head1 = null ;
Node head2 = null ;
head1 = push(head1, 17 );
head1 = push(head1, 10 );
head1 = push(head1, 12 );
head1 = push(head1, 4 );
head1 = push(head1, 3 );
head2 = push(head2, 12 );
head2 = push(head2, 34 );
head2 = push(head2, 575 );
head2 = push(head2, 8 );
head2 = push(head2, 4 );
head2 = push(head2, 10 );
System.out.print( "Given Linked List A: \n" );
printList(head1);
System.out.print( "Given Linked List B: \n" );
printList(head2);
int count = countCommonNodes(head1, head2);
System.out.print( "Number of common node in both list is = " + count);
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
def countCommonNodes(head1, head2):
current1 = head1
current2 = head2
count = 0
while (current1 ! = None ):
while (current2 ! = None ):
if (current1.data = = current2.data):
count = count + 1
current2 = current2. next
current1 = current1. next
current2 = head2
return count
def push(head_ref, new_data):
new_node = Node( 0 )
new_node.data = new_data
new_node. next = head_ref
head_ref = new_node
return head_ref
def printList( head):
while (head ! = None ):
print (head.data, end = " " )
head = head. next
print ("")
if __name__ = = '__main__' :
head1 = None
head2 = None
head1 = push(head1, 17 )
head1 = push(head1, 10 )
head1 = push(head1, 12 )
head1 = push(head1, 4 )
head1 = push(head1, 3 )
head2 = push(head2, 12 )
head2 = push(head2, 34 )
head2 = push(head2, 575 )
head2 = push(head2, 8 )
head2 = push(head2, 4 )
head2 = push(head2, 10 )
print ( "Given Linked List A: " )
printList(head1)
print ( "Given Linked List B: " )
printList(head2)
count = countCommonNodes(head1, head2)
print ( "Number of common node in both list is = " , count)
|
C#
using System;
class GFG {
public class Node {
public int data;
public Node next;
};
static int countCommonNodes(Node head1, Node head2)
{
Node current1 = head1;
Node current2 = head2;
int count = 0;
while (current1 != null ) {
while (current2 != null ) {
if (current1.data == current2.data)
count++;
current2 = current2.next;
}
current1 = current1.next;
current2 = head2;
}
return count;
}
static Node push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
static void printList(Node head)
{
while (head != null ) {
Console.Write(head.data + " " );
head = head.next;
}
Console.WriteLine();
}
public static void Main(String[] args)
{
Node head1 = null ;
Node head2 = null ;
head1 = push(head1, 17);
head1 = push(head1, 10);
head1 = push(head1, 12);
head1 = push(head1, 4);
head1 = push(head1, 3);
head2 = push(head2, 12);
head2 = push(head2, 34);
head2 = push(head2, 575);
head2 = push(head2, 8);
head2 = push(head2, 4);
head2 = push(head2, 10);
Console.Write( "Given Linked List A: \n" );
printList(head1);
Console.Write( "Given Linked List B: \n" );
printList(head2);
int count = countCommonNodes(head1, head2);
Console.Write( "Number of common node in both list is = " + count);
}
}
|
Javascript
<script>
class Node
{
constructor(val)
{
this .data = val;
this .next = null ;
}
}
function countCommonNodes(head1, head2)
{
var current1 = head1;
var current2 = head2;
var count = 0;
while (current1 != null )
{
while (current2 != null )
{
if (current1.data == current2.data)
count++;
current2 = current2.next;
}
current1 = current1.next;
current2 = head2;
}
return count;
}
function push(head_ref, new_data)
{
var new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
function printList(head)
{
while (head != null )
{
document.write(head.data + " " );
head = head.next;
}
document.write( "<br/>" );
}
var head1 = null ;
var head2 = null ;
head1 = push(head1, 17);
head1 = push(head1, 10);
head1 = push(head1, 12);
head1 = push(head1, 4);
head1 = push(head1, 3);
head2 = push(head2, 12);
head2 = push(head2, 34);
head2 = push(head2, 575);
head2 = push(head2, 8);
head2 = push(head2, 4);
head2 = push(head2, 10);
document.write( "Given Linked List A: <br/>" );
printList(head1);
document.write( "Given Linked List B: <br/>" );
printList(head2);
var count = countCommonNodes(head1, head2);
document.write( "Number of common node in both list is = " +
count);
</script>
|
Output
Given Linked List A:
3 4 12 10 17
Given Linked List B:
10 4 8 575 34 12
Number of common node in both list is = 3
Complexity Analysis:
- Time Complexity: O(M*N), where M is length of list A and N is length of list B
- Auxiliary Space: O(1) because it is using constant space
Efficient Solution: Insert all the nodes of linked list A in the unordered_set and then check for each node of linked list B in unordered_set. If found increment the count and return the count at the end.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
int countCommonNodes( struct Node* head1, struct Node* head2)
{
struct Node* current1 = head1;
struct Node* current2 = head2;
int count = 0;
unordered_set< int > map;
while (current1 != NULL) {
map.insert(current1->data);
current1 = current1->next;
}
while (current2 != NULL) {
if (map.find(current2->data) != map.end())
count++;
current2 = current2->next;
}
return count;
}
void push( struct Node** head_ref, int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
void printList( struct Node* head)
{
while (head != NULL) {
cout << head->data << " " ;
head = head->next;
}
cout << endl;
}
int main()
{
struct Node* head1 = NULL;
struct Node* head2 = NULL;
push(&head1, 17);
push(&head1, 10);
push(&head1, 12);
push(&head1, 4);
push(&head1, 3);
push(&head2, 12);
push(&head2, 34);
push(&head2, 575);
push(&head2, 8);
push(&head2, 4);
push(&head2, 10);
cout << "Given Linked List A: \n" ;
printList(head1);
cout << "Given Linked List B: \n" ;
printList(head2);
int count = countCommonNodes(head1, head2);
cout << "Number of common node in both list is = " << count;
return 0;
}
|
Java
import java.util.*;
class solution {
static class Node {
int data;
Node next;
}
static int countCommonNodes(Node head1, Node head2)
{
Node current1 = head1;
Node current2 = head2;
int count = 0 ;
Vector<Integer> map = new Vector<Integer>();
while (current1 != null ) {
map.add(current1.data);
current1 = current1.next;
}
while (current2 != null ) {
if (map.contains(current2.data))
count++;
current2 = current2.next;
}
return count;
}
static Node push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
static void printList(Node head)
{
while (head != null ) {
System.out.print(head.data + " " );
head = head.next;
}
System.out.println();
}
public static void main(String args[])
{
Node head1 = null ;
Node head2 = null ;
head1 = push(head1, 17 );
head1 = push(head1, 10 );
head1 = push(head1, 12 );
head1 = push(head1, 4 );
head1 = push(head1, 3 );
head2 = push(head2, 12 );
head2 = push(head2, 34 );
head2 = push(head2, 575 );
head2 = push(head2, 8 );
head2 = push(head2, 4 );
head2 = push(head2, 10 );
System.out.print( "Given Linked List A: \n" );
printList(head1);
System.out.print( "Given Linked List B: \n" );
printList(head2);
int count = countCommonNodes(head1, head2);
System.out.print( "Number of common node in both list is = " + count);
}
}
|
Python3
class Node:
def __init__( self ):
self .data = 0
self . next = None
def countCommonNodes(head1, head2):
current1 = head1
current2 = head2
count = 0
map_ = set ()
while (current1 ! = None ) :
map_.add(current1.data)
current1 = current1. next
while (current2 ! = None ) :
if ((current2.data) in map_):
count = count + 1
current2 = current2. next
return count
def push(head_ref,new_data):
new_node = Node()
new_node.data = new_data
new_node. next = head_ref
head_ref = new_node
return head_ref
def printList(head):
while (head ! = None ) :
print (head.data, end = " " )
head = head. next
head1 = None
head2 = None
head1 = push(head1, 17 )
head1 = push(head1, 10 )
head1 = push(head1, 12 )
head1 = push(head1, 4 )
head1 = push(head1, 3 )
head2 = push(head2, 12 )
head2 = push(head2, 34 )
head2 = push(head2, 575 )
head2 = push(head2, 8 )
head2 = push(head2, 4 )
head2 = push(head2, 10 )
print ( "Given Linked List A: " )
printList(head1)
print ( "\nGiven Linked List B: " )
printList(head2)
count = countCommonNodes(head1, head2)
print ( "\nNumber of common node in both list is = " , count)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public class Node
{
public int data;
public Node next;
}
static int countCommonNodes(Node head1, Node head2)
{
Node current1 = head1;
Node current2 = head2;
int count = 0;
List< int > map = new List< int >();
while (current1 != null )
{
map.Add(current1.data);
current1 = current1.next;
}
while (current2 != null )
{
if (map.Contains(current2.data))
count++;
current2 = current2.next;
}
return count;
}
static Node push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
static void printList(Node head)
{
while (head != null )
{
Console.Write(head.data + " " );
head = head.next;
}
Console.WriteLine();
}
public static void Main(String []args)
{
Node head1 = null ;
Node head2 = null ;
head1 = push(head1, 17);
head1 = push(head1, 10);
head1 = push(head1, 12);
head1 = push(head1, 4);
head1 = push(head1, 3);
head2 = push(head2, 12);
head2 = push(head2, 34);
head2 = push(head2, 575);
head2 = push(head2, 8);
head2 = push(head2, 4);
head2 = push(head2, 10);
Console.Write( "Given Linked List A: \n" );
printList(head1);
Console.Write( "Given Linked List B: \n" );
printList(head2);
int count = countCommonNodes(head1, head2);
Console.Write( "Number of common node in both list is = " + count);
}
}
|
Javascript
<script>
class Node {
constructor() {
this .data = 0;
this .next = null ;
}
}
function countCommonNodes(head1, head2) {
var current1 = head1;
var current2 = head2;
var count = 0;
var map = [];
while (current1 != null ) {
map.push(current1.data);
current1 = current1.next;
}
while (current2 != null ) {
if (map.includes(current2.data)) count++;
current2 = current2.next;
}
return count;
}
function push(head_ref, new_data) {
var new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
function printList(head) {
while (head != null ) {
document.write(head.data + " " );
head = head.next;
}
document.write( "<br>" );
}
var head1 = null ;
var head2 = null ;
head1 = push(head1, 17);
head1 = push(head1, 10);
head1 = push(head1, 12);
head1 = push(head1, 4);
head1 = push(head1, 3);
head2 = push(head2, 12);
head2 = push(head2, 34);
head2 = push(head2, 575);
head2 = push(head2, 8);
head2 = push(head2, 4);
head2 = push(head2, 10);
document.write( "Given Linked List A: <br>" );
printList(head1);
document.write( "Given Linked List B: <br>" );
printList(head2);
var count = countCommonNodes(head1, head2);
document.write( "Number of common node in both list is = " + count);
</script>
|
Output
Given Linked List A:
3 4 12 10 17
Given Linked List B:
10 4 8 575 34 12
Number of common node in both list is = 3
Complexity Analysis:
- Time Complexity: O(N)
- Space Complexity: O(N)
Recursive Approach:
- Check if either of the linked lists is empty (i.e., head1 or head2 is null), return 0 if either of them is empty.
- Initialize a count variable to 0, and create a Node pointer temp to point to the head of the second linked list.
- Traverse the second linked list using temp, comparing each node’s data with the data of the current node of the first linked list (i.e., head1). If there is a match, increment the count.
- Recursively call the countCommonNodes function, passing in the next node of the first linked list (i.e., head1->next) and the head of the second linked list (i.e., head2).
- Add the count returned by the recursive call to the count variable.
- Return the final count.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
int countCommonNodes(Node* head1, Node* head2) {
if (head1 == nullptr || head2 == nullptr) {
return 0;
}
int count = 0;
Node* temp = head2;
while (temp != nullptr) {
if (head1->data == temp->data) {
count++;
}
temp = temp->next;
}
return count + countCommonNodes(head1->next, head2);
}
Node* newNode( int data) {
Node* node = new Node;
node->data = data;
node->next = nullptr;
return node;
}
void printList( struct Node* head)
{
while (head != NULL) {
cout << head->data << " " ;
head = head->next;
}
cout << endl;
}
int main() {
Node* head1 = newNode(3);
head1->next = newNode(4);
head1->next->next = newNode(12);
head1->next->next->next = newNode(10);
head1->next->next->next->next = newNode(17);
Node* head2 = newNode(10);
head2->next = newNode(4);
head2->next->next = newNode(8);
head2->next->next->next = newNode(575);
head2->next->next->next->next = newNode(34);
head2->next->next->next->next->next = newNode(12);
cout << "Given Linked List A: \n" ;
printList(head1);
cout << "Given Linked List B: \n" ;
printList(head2);
int count = countCommonNodes(head1, head2);
cout << "Number of common node in both list is = " << count;
return 0;
}
|
Java
class Node {
int data;
Node next;
public Node( int data) {
this .data = data;
this .next = null ;
}
}
public class LinkedListCommonNodes {
public static int countCommonNodes(Node head1, Node head2) {
if (head1 == null || head2 == null ) {
return 0 ;
}
int count = 0 ;
Node temp = head2;
while (temp != null ) {
if (head1.data == temp.data) {
count++;
}
temp = temp.next;
}
return count + countCommonNodes(head1.next, head2);
}
public static void printList(Node head) {
while (head != null ) {
System.out.print(head.data + " " );
head = head.next;
}
System.out.println();
}
public static void main(String[] args) {
Node head1 = new Node( 3 );
head1.next = new Node( 4 );
head1.next.next = new Node( 12 );
head1.next.next.next = new Node( 10 );
head1.next.next.next.next = new Node( 17 );
Node head2 = new Node( 10 );
head2.next = new Node( 4 );
head2.next.next = new Node( 8 );
head2.next.next.next = new Node( 575 );
head2.next.next.next.next = new Node( 34 );
head2.next.next.next.next.next = new Node( 12 );
System.out.println( "Given Linked List A:" );
printList(head1);
System.out.println( "Given Linked List B:" );
printList(head2);
int count = countCommonNodes(head1, head2);
System.out.println( "Number of common nodes in both lists is = " + count);
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
def count_common_nodes(head1, head2):
if head1 is None or head2 is None :
return 0
count = 0
temp = head2
while temp is not None :
if head1.data = = temp.data:
count + = 1
temp = temp. next
return count + count_common_nodes(head1. next , head2)
def print_list(head):
while head is not None :
print (head.data, end = " " )
head = head. next
print ()
if __name__ = = "__main__" :
head1 = Node( 3 )
head1. next = Node( 4 )
head1. next . next = Node( 12 )
head1. next . next . next = Node( 10 )
head1. next . next . next . next = Node( 17 )
head2 = Node( 10 )
head2. next = Node( 4 )
head2. next . next = Node( 8 )
head2. next . next . next = Node( 575 )
head2. next . next . next . next = Node( 34 )
head2. next . next . next . next . next = Node( 12 )
print ( "Given Linked List A:" )
print_list(head1)
print ( "Given Linked List B:" )
print_list(head2)
count = count_common_nodes(head1, head2)
print ( "Number of common nodes in both lists is =" , count)
|
C#
using System;
public class Node
{
public int data;
public Node next;
}
public class LinkedListIntersection
{
public static int CountCommonNodes(Node head1, Node head2)
{
if (head1 == null || head2 == null )
{
return 0;
}
int count = 0;
Node temp = head2;
while (temp != null )
{
if (head1.data == temp.data)
{
count++;
}
temp = temp.next;
}
return count + CountCommonNodes(head1.next, head2);
}
public static Node NewNode( int data)
{
Node node = new Node();
node.data = data;
node.next = null ;
return node;
}
public static void PrintList(Node head)
{
while (head != null )
{
Console.Write(head.data + " " );
head = head.next;
}
Console.WriteLine();
}
public static void Main( string [] args)
{
Node head1 = NewNode(3);
head1.next = NewNode(4);
head1.next.next = NewNode(12);
head1.next.next.next = NewNode(10);
head1.next.next.next.next = NewNode(17);
Node head2 = NewNode(10);
head2.next = NewNode(4);
head2.next.next = NewNode(8);
head2.next.next.next = NewNode(575);
head2.next.next.next.next = NewNode(34);
head2.next.next.next.next.next = NewNode(12);
Console.WriteLine( "Given Linked List A:" );
PrintList(head1);
Console.WriteLine( "Given Linked List B:" );
PrintList(head2);
int count = CountCommonNodes(head1, head2);
Console.WriteLine( "Number of common nodes in both lists = " + count);
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .next = null ;
}
}
function countCommonNodes(head1, head2) {
if (head1 === null || head2 === null ) {
return 0;
}
let count = 0;
let temp = head2;
while (temp !== null ) {
if (head1.data === temp.data) {
count++;
}
temp = temp.next;
}
return count + countCommonNodes(head1.next, head2);
}
function printList(head) {
while (head !== null ) {
process.stdout.write(head.data + " " );
head = head.next;
}
console.log();
}
if ( typeof require !== 'undefined' && require.main === module) {
const head1 = new Node(3);
head1.next = new Node(4);
head1.next.next = new Node(12);
head1.next.next.next = new Node(10);
head1.next.next.next.next = new Node(17);
const head2 = new Node(10);
head2.next = new Node(4);
head2.next.next = new Node(8);
head2.next.next.next = new Node(575);
head2.next.next.next.next = new Node(34);
head2.next.next.next.next.next = new Node(12);
console.log( "Given Linked List A:" );
printList(head1);
console.log( "Given Linked List B:" );
printList(head2);
const count = countCommonNodes(head1, head2);
console.log( "Number of common nodes in both lists is =" , count);
}
|
Output:
Given Linked List A:
3 4 12 10 17
Given Linked List B:
10 4 8 575 34 12
Number of common node in both list is = 3
Time Complexity: O(m*n), where m and n are the lengths of the two lists respectively. This is because, for each node in the first list, we need to traverse the entire second list to check if there are any common nodes.
Auxiliary Space: O(m+n), where m and n are the lengths of the two lists respectively. This is because we are using the call stack to keep track of the recursion, and the maximum depth of the recursion tree is m+n.
Last Updated :
25 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...