Find the common nodes in two singly linked list
Last Updated :
25 Sep, 2023
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++
// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
// Structure of a linked list node
struct Node {
int data;
struct Node* next;
};
// Function to common nodes which have
// same value node(s) both list
int countCommonNodes(struct Node* head1, struct Node* head2)
{
// list A
struct Node* current1 = head1;
// list B
struct Node* current2 = head2;
// set count = 0
int count = 0;
// traverse list A till the end of list
while (current1 != NULL) {
// traverse list B till the end of list
while (current2 != NULL) {
// if data is match then count increase
if (current1->data == current2->data)
count++;
// increase current pointer for next node
current2 = current2->next;
}
// increase current pointer of list A
current1 = current1->next;
// initialize list B starting point
current2 = head2;
}
// return count
return count;
}
/* Utility function to insert a node at the beginning */
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;
}
/* Utility function to print a linked list */
void printList(struct Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
/* Driver program to test above functions */
int main()
{
struct Node* head1 = NULL;
struct Node* head2 = NULL;
/* Create following linked list
List A = 3 -> 4 -> 12 -> 10 -> 17
*/
push(&head1, 17);
push(&head1, 10);
push(&head1, 12);
push(&head1, 4);
push(&head1, 3);
// List B = 10 -> 4 -> 8 -> 575 -> 34 -> 12
push(&head2, 12);
push(&head2, 34);
push(&head2, 575);
push(&head2, 8);
push(&head2, 4);
push(&head2, 10);
// print list A
cout << "Given Linked List A: \n";
printList(head1);
// print list B
cout << "Given Linked List B: \n";
printList(head2);
// call function for count common node
int count = countCommonNodes(head1, head2);
// print number of common node in both list
cout << "Number of common node in both list is = " << count;
return 0;
}
Java
// Java implementation of above approach
class GFG {
// Structure of a linked list node
static class Node {
int data;
Node next;
};
// Function to common nodes which have
// same value node(s) both list
static int countCommonNodes(Node head1, Node head2)
{
// list A
Node current1 = head1;
// list B
Node current2 = head2;
// set count = 0
int count = 0;
// traverse list A till the end of list
while (current1 != null) {
// traverse list B till the end of list
while (current2 != null) {
// if data is match then count increase
if (current1.data == current2.data)
count++;
// increase current pointer for next node
current2 = current2.next;
}
// increase current pointer of list A
current1 = current1.next;
// initialize list B starting point
current2 = head2;
}
// return count
return count;
}
// Utility function to insert a node at the beginning /
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;
}
// Utility function to print a linked list
static void printList(Node head)
{
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
System.out.println();
}
// Driver code
public static void main(String args[])
{
Node head1 = null;
Node head2 = null;
// Create following linked list
// List A = 3 . 4 . 12 . 10 . 17
head1 = push(head1, 17);
head1 = push(head1, 10);
head1 = push(head1, 12);
head1 = push(head1, 4);
head1 = push(head1, 3);
// List B = 10 . 4 . 8 . 575 . 34 . 12
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 list A
System.out.print("Given Linked List A: \n");
printList(head1);
// print list B
System.out.print("Given Linked List B: \n");
printList(head2);
// call function for count common node
int count = countCommonNodes(head1, head2);
// print number of common node in both list
System.out.print("Number of common node in both list is = " + count);
}
}
// This code is contributed by Arnab Kundu
Python3
# Python3 implementation of above approach
# Link list node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to common nodes which have
# same value node(s) both list
def countCommonNodes(head1, head2):
# list A
current1 = head1
# list B
current2 = head2
# set count = 0
count = 0
# traverse list A till the end of list
while (current1 != None):
# traverse list B till the end of list
while (current2 != None):
# if data is match then count increase
if (current1.data == current2.data):
count = count + 1
# increase current pointer for next node
current2 = current2.next
# increase current pointer of list A
current1 = current1.next
# initialize list B starting point
current2 = head2
# return count
return count
# Utility function to insert a node at the beginning
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
# Utility function to print a linked list
def printList( head):
while (head != None):
print(head.data, end = " ")
head = head.next
print("")
# Driver Code
if __name__=='__main__':
head1 = None
head2 = None
# Create following linked list
# List A = 3 . 4 . 12 . 10 . 17
head1 = push(head1, 17)
head1 = push(head1, 10)
head1 = push(head1, 12)
head1 = push(head1, 4)
head1 = push(head1, 3)
# List B = 10 . 4 . 8 . 575 . 34 . 12
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 list A
print("Given Linked List A: ")
printList(head1)
# print list B
print("Given Linked List B: ")
printList(head2)
# call function for count common node
count = countCommonNodes(head1, head2)
# print number of common node in both list
print("Number of common node in both list is = ", count)
# This code is contributed by Arnab Kundu
C#
// C# implementation of the approach
using System;
class GFG {
// Structure of a linked list node
public class Node {
public int data;
public Node next;
};
// Function to common nodes which have
// same value node(s) both list
static int countCommonNodes(Node head1, Node head2)
{
// list A
Node current1 = head1;
// list B
Node current2 = head2;
// set count = 0
int count = 0;
// traverse list A till the end of list
while (current1 != null) {
// traverse list B till the end of list
while (current2 != null) {
// if data is match then count increase
if (current1.data == current2.data)
count++;
// increase current pointer for next node
current2 = current2.next;
}
// increase current pointer of list A
current1 = current1.next;
// initialize list B starting point
current2 = head2;
}
// return count
return count;
}
// Utility function to insert a node at the beginning /
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;
}
// Utility function to print a linked list
static void printList(Node head)
{
while (head != null) {
Console.Write(head.data + " ");
head = head.next;
}
Console.WriteLine();
}
// Driver code
public static void Main(String[] args)
{
Node head1 = null;
Node head2 = null;
// Create following linked list
// List A = 3 . 4 . 12 . 10 . 17
head1 = push(head1, 17);
head1 = push(head1, 10);
head1 = push(head1, 12);
head1 = push(head1, 4);
head1 = push(head1, 3);
// List B = 10 . 4 . 8 . 575 . 34 . 12
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 list A
Console.Write("Given Linked List A: \n");
printList(head1);
// print list B
Console.Write("Given Linked List B: \n");
printList(head2);
// call function for count common node
int count = countCommonNodes(head1, head2);
// print number of common node in both list
Console.Write("Number of common node in both list is = " + count);
}
}
/* This code contributed by PrinciRaj1992 */
JavaScript
<script>
// Javascript implementation of above approach
// Structure of a linked list node
class Node
{
constructor(val)
{
this.data = val;
this.next = null;
}
}
// Function to common nodes which have
// same value node(s) both list
function countCommonNodes(head1, head2)
{
// List A
var current1 = head1;
// List B
var current2 = head2;
// Set count = 0
var count = 0;
// Traverse list A till the end of list
while (current1 != null)
{
// Traverse list B till the end of list
while (current2 != null)
{
// If data is match then count increase
if (current1.data == current2.data)
count++;
// Increase current pointer for next node
current2 = current2.next;
}
// Increase current pointer of list A
current1 = current1.next;
// Initialize list B starting point
current2 = head2;
}
// Return count
return count;
}
// Utility function to insert a node at the beginning
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;
}
// Utility function to print a linked list
function printList(head)
{
while (head != null)
{
document.write(head.data + " ");
head = head.next;
}
document.write("<br/>");
}
// Driver code
var head1 = null;
var head2 = null;
// Create following linked list
// List A = 3 . 4 . 12 . 10 . 17
head1 = push(head1, 17);
head1 = push(head1, 10);
head1 = push(head1, 12);
head1 = push(head1, 4);
head1 = push(head1, 3);
// List B = 10 . 4 . 8 . 575 . 34 . 12
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 list A
document.write("Given Linked List A: <br/>");
printList(head1);
// Print list B
document.write("Given Linked List B: <br/>");
printList(head2);
// Call function for count common node
var count = countCommonNodes(head1, head2);
// Print number of common node in both list
document.write("Number of common node in both list is = " +
count);
// This code is contributed by gauravrajput1
</script>
OutputGiven 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++
// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
// Structure of a linked list node
struct Node {
int data;
struct Node* next;
};
// Function to common nodes which have
// same value node(s) both list
int countCommonNodes(struct Node* head1, struct Node* head2)
{
// list A
struct Node* current1 = head1;
// list B
struct Node* current2 = head2;
// set count = 0
int count = 0;
// create unordered_set
unordered_set<int> map;
// traverse list A till the end of list
while (current1 != NULL) {
// insert list data in map
map.insert(current1->data);
// increase current pointer of list A
current1 = current1->next;
}
while (current2 != NULL) {
// traverse list B till the end of list
// if data match then increase count
if (map.find(current2->data) != map.end())
count++;
// increase current pointer of list B
current2 = current2->next;
}
// return count
return count;
}
/* Utility function to insert a node at the beginning */
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;
}
/* Utility function to print a linked list */
void printList(struct Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
/* Driver program to test above functions */
int main()
{
struct Node* head1 = NULL;
struct Node* head2 = NULL;
/* Create following linked list
List A = 3 -> 4 -> 12 -> 10 -> 17
*/
push(&head1, 17);
push(&head1, 10);
push(&head1, 12);
push(&head1, 4);
push(&head1, 3);
// List B = 10 -> 4 -> 8 -> 575 -> 34 -> 12
push(&head2, 12);
push(&head2, 34);
push(&head2, 575);
push(&head2, 8);
push(&head2, 4);
push(&head2, 10);
// print list A
cout << "Given Linked List A: \n";
printList(head1);
// print list B
cout << "Given Linked List B: \n";
printList(head2);
// call function for count common node
int count = countCommonNodes(head1, head2);
// print number of common node in both list
cout << "Number of common node in both list is = " << count;
return 0;
}
Java
// Java implementation of above approach
import java.util.*;
class solution {
// static class of a linked list node
static class Node {
int data;
Node next;
}
// Function to common nodes which have
// same value node(s) both list
static int countCommonNodes(Node head1, Node head2)
{
// list A
Node current1 = head1;
// list B
Node current2 = head2;
// set count = 0
int count = 0;
// create vector
Vector<Integer> map = new Vector<Integer>();
// traverse list A till the end of list
while (current1 != null) {
// insert list data in map
map.add(current1.data);
// increase current pointer of list A
current1 = current1.next;
}
while (current2 != null) {
// traverse list B till the end of list
// if data match then increase count
if (map.contains(current2.data))
count++;
// increase current pointer of list B
current2 = current2.next;
}
// return count
return count;
}
/* Utility function to insert a node at the beginning */
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;
}
/* Utility function to print a linked list */
static void printList(Node head)
{
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
System.out.println();
}
/* Driver program to test above functions */
public static void main(String args[])
{
Node head1 = null;
Node head2 = null;
/* Create following linked list
List A = 3 . 4 . 12 . 10 . 17
*/
head1 = push(head1, 17);
head1 = push(head1, 10);
head1 = push(head1, 12);
head1 = push(head1, 4);
head1 = push(head1, 3);
// List B = 10 . 4 . 8 . 575 . 34 . 12
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 list A
System.out.print("Given Linked List A: \n");
printList(head1);
// print list B
System.out.print("Given Linked List B: \n");
printList(head2);
// call function for count common node
int count = countCommonNodes(head1, head2);
// print number of common node in both list
System.out.print("Number of common node in both list is = " + count);
}
}
// This code is contributed by Arnab Kundu
Python3
# Python3 implementation of the approach
# Structure of a linked list node
class Node:
def __init__(self):
self.data = 0
self.next = None
# Function to common nodes which have
# same value node(s) both list
def countCommonNodes(head1, head2):
# List A
current1 = head1
# List B
current2 = head2
# Set count = 0
count = 0
# Create unordered_set
map_=set()
# Traverse list A till the end of list
while (current1 != None) :
# Add list data in map_
map_.add(current1.data)
# Increase current pointer of list A
current1 = current1.next
while (current2 != None) :
# Traverse list B till the end of list
# if data match then increase count
if ((current2.data) in map_):
count = count + 1
# Increase current pointer of list B
current2 = current2.next
# Return count
return count
# Utility function to add a node at the beginning
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
# Utility function to print a linked list
def printList(head):
while (head != None) :
print(head.data, end = " ")
head = head.next
# Driver program to test above functions
head1 = None
head2 = None
# Create following linked list
# List A = 3 . 4 . 12 . 10 . 17
head1 = push(head1, 17)
head1 = push(head1, 10)
head1 = push(head1, 12)
head1 = push(head1, 4)
head1 = push(head1, 3)
# List B = 10 . 4 . 8 . 575 . 34 . 12
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 list A
print("Given Linked List A: ")
printList(head1)
# Print list B
print( "\nGiven Linked List B: ")
printList(head2)
# Call function for count common node
count = countCommonNodes(head1, head2)
# Print number of common node in both list
print("\nNumber of common node in both list is = " , count)
# This code is contributed by Arnab Kundu
C#
// C# implementation of above approach
using System;
using System.Collections.Generic;
class GFG
{
// static class of a linked list node
public class Node
{
public int data;
public Node next;
}
// Function to common nodes which have
// same value node(s) both list
static int countCommonNodes(Node head1, Node head2)
{
// list A
Node current1 = head1;
// list B
Node current2 = head2;
// set count = 0
int count = 0;
// create vector
List<int> map = new List<int>();
// traverse list A till the end of list
while (current1 != null)
{
// insert list data in map
map.Add(current1.data);
// increase current pointer of list A
current1 = current1.next;
}
while (current2 != null)
{
// traverse list B till the end of list
// if data match then increase count
if (map.Contains(current2.data))
count++;
// increase current pointer of list B
current2 = current2.next;
}
// return count
return count;
}
/* Utility function to insert a node at the beginning */
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;
}
/* Utility function to print a linked list */
static void printList(Node head)
{
while (head != null)
{
Console.Write(head.data + " ");
head = head.next;
}
Console.WriteLine();
}
/* Driver code */
public static void Main(String []args)
{
Node head1 = null;
Node head2 = null;
/* Create following linked list
List A = 3 . 4 . 12 . 10 . 17
*/
head1 = push(head1, 17);
head1 = push(head1, 10);
head1 = push(head1, 12);
head1 = push(head1, 4);
head1 = push(head1, 3);
// List B = 10 . 4 . 8 . 575 . 34 . 12
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 list A
Console.Write("Given Linked List A: \n");
printList(head1);
// print list B
Console.Write("Given Linked List B: \n");
printList(head2);
// call function for count common node
int count = countCommonNodes(head1, head2);
// print number of common node in both list
Console.Write("Number of common node in both list is = " + count);
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// JavaScript implementation of above approach
// static class of a linked list node
class Node {
constructor() {
this.data = 0;
this.next = null;
}
}
// Function to common nodes which have
// same value node(s) both list
function countCommonNodes(head1, head2) {
// list A
var current1 = head1;
// list B
var current2 = head2;
// set count = 0
var count = 0;
// create vector
var map = [];
// traverse list A till the end of list
while (current1 != null) {
// insert list data in map
map.push(current1.data);
// increase current pointer of list A
current1 = current1.next;
}
while (current2 != null) {
// traverse list B till the end of list
// if data match then increase count
if (map.includes(current2.data)) count++;
// increase current pointer of list B
current2 = current2.next;
}
// return count
return count;
}
/* Utility function to insert a node at the beginning */
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;
}
/* Utility function to print a linked list */
function printList(head) {
while (head != null) {
document.write(head.data + " ");
head = head.next;
}
document.write("<br>");
}
/* Driver code */
var head1 = null;
var head2 = null;
/* Create following linked list
List A = 3 . 4 . 12 . 10 . 17
*/
head1 = push(head1, 17);
head1 = push(head1, 10);
head1 = push(head1, 12);
head1 = push(head1, 4);
head1 = push(head1, 3);
// List B = 10 . 4 . 8 . 575 . 34 . 12
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 list A
document.write("Given Linked List A: <br>");
printList(head1);
// print list B
document.write("Given Linked List B: <br>");
printList(head2);
// call function for count common node
var count = countCommonNodes(head1, head2);
// print number of common node in both list
document.write("Number of common node in both list is = " + count);
// This code is contributed by rdtank.
</script>
OutputGiven 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;
// Node structure
struct Node {
int data;
Node* next;
};
// Function to find the intersection of two linked lists recursively
int countCommonNodes(Node* head1, Node* head2) {
// If either of the lists is empty, there can't be any common nodes
if (head1 == nullptr || head2 == nullptr) {
return 0;
}
// Check if the current node of the first list appears in the second list
int count = 0;
Node* temp = head2;
while (temp != nullptr) {
if (head1->data == temp->data) {
count++;
}
temp = temp->next;
}
// Recursively check for common nodes in the rest of the lists
return count + countCommonNodes(head1->next, head2);
}
// Function to create a new node
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;
}
// Driver code
int main() {
// Create first linked list
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);
// Create second linked list
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);
// print list A
cout << "Given Linked List A: \n";
printList(head1);
// print list B
cout << "Given Linked List B: \n";
printList(head2);
// call function for count common node
int count = countCommonNodes(head1, head2);
// print number of common node in both list
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 either of the lists is empty, there can't be any common nodes
if (head1 == null || head2 == null) {
return 0;
}
// Check if the current node of the first list appears in the second list
int count = 0;
Node temp = head2;
while (temp != null) {
if (head1.data == temp.data) {
count++;
}
temp = temp.next;
}
// Recursively check for common nodes in the rest of the lists
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) {
// Create first linked list
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);
// Create second linked list
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);
// Print list A
System.out.println("Given Linked List A:");
printList(head1);
// Print list B
System.out.println("Given Linked List B:");
printList(head2);
// Call function to count common nodes
int count = countCommonNodes(head1, head2);
// Print the number of common nodes in both lists
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 either of the lists is empty, there can't be any common nodes
if head1 is None or head2 is None:
return 0
# Check if the current node of the first list appears in the second list
count = 0
temp = head2
while temp is not None:
if head1.data == temp.data:
count += 1
temp = temp.next
# Recursively check for common nodes in the rest of the lists
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()
# Driver code
if __name__ == "__main__":
# Create first linked list
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)
# Create second linked list
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 list A
print("Given Linked List A:")
print_list(head1)
# Print list B
print("Given Linked List B:")
print_list(head2)
# Call function to count common nodes
count = count_common_nodes(head1, head2)
# Print the number of common nodes in both lists
print("Number of common nodes in both lists is =", count)
C#
using System;
// Node structure
public class Node
{
public int data;
public Node next;
}
public class LinkedListIntersection
{
// Function to find the intersection of two linked lists recursively
public static int CountCommonNodes(Node head1, Node head2)
{
// If either of the lists is empty, there can't be any common nodes
if (head1 == null || head2 == null)
{
return 0;
}
// Check if the current node of the first list appears in the second list
int count = 0;
Node temp = head2;
while (temp != null)
{
if (head1.data == temp.data)
{
count++;
}
temp = temp.next;
}
// Recursively check for common nodes in the rest of the lists
return count + CountCommonNodes(head1.next, head2);
}
// Function to create a new node
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();
}
// Driver code
public static void Main(string[] args)
{
// Create first linked list
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);
// Create second linked list
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);
// Print list A
Console.WriteLine("Given Linked List A:");
PrintList(head1);
// Print list B
Console.WriteLine("Given Linked List B:");
PrintList(head2);
// Call function for count common node
int count = CountCommonNodes(head1, head2);
// Print number of common nodes in both lists
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 either of the lists is empty, there can't be any common nodes
if (head1 === null || head2 === null) {
return 0;
}
// Check if the current node of the first list appears in the second list
let count = 0;
let temp = head2;
while (temp !== null) {
if (head1.data === temp.data) {
count++;
}
temp = temp.next;
}
// Recursively check for common nodes in the rest of the lists
return count + countCommonNodes(head1.next, head2);
}
function printList(head) {
while (head !== null) {
process.stdout.write(head.data + " ");
head = head.next;
}
console.log();
}
// Driver code
if (typeof require !== 'undefined' && require.main === module) {
// Create first linked list
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);
// Create second linked list
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);
// Print list A
console.log("Given Linked List A:");
printList(head1);
// Print list B
console.log("Given Linked List B:");
printList(head2);
// Call function to count common nodes
const count = countCommonNodes(head1, head2);
// Print the number of common nodes in both lists
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.
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