Find count of common nodes in two Doubly Linked Lists
Last Updated :
08 Oct, 2023
Given two doubly linked lists. The task is to find the total number of common nodes in both the doubly linked list.
Examples:
Input :
list 1 = 15 <=> 16 <=> 10 <=> 9 <=> 6 <=> 7 <=> 17
list 2 = 15 <=> 16 <=> 45 <=> 9 <=> 6
Output : Number of common nodes: 4
Input :
list 1 = 18 <=> 30 <=> 92 <=> 46 <=> 72 <=> 1
list 2 = 12 <=> 32 <=> 45 <=> 9 <=> 6 <=> 30
Output : Number of common nodes: 1
Approach 1: Traverse both lists till the end of the list using two nested loops. For every node in list 1 check if it matches with any node in list 2. If yes then increment the count of common nodes. Finally, print the count.
Algorithm:
- Create a function called “push” that adds a new node to the doubly linked list’s beginning. The function requires two arguments: new data and head ref (a pointer to the list’s head) (the data value to be inserted). The updated head pointer is returned by the function.
- Create a function called “countCommonNodes” that accepts the parameters head ref (a pointer to the first doubly linked list’s head) and head (pointer to the head of the second doubly linked list). The number of shared nodes between the two lists is represented as an integer by the function’s output. s.
- Set up two pointers, ptr, and ptr1, to point to the respective heads of the two lists.
- Set the count variable’s initial value to 0.
- Use ptr to navigate through the first list to the very end.
- Up to the list’s conclusion, traverse the second list using ptr1.
- Increase the count and exit the inner loop if the data value of the current node in the first list equals the data value of the current node in the second list.
- Reset ptr1 to the head of the second list.
- Move ptr to the next node in the first list.
- Repeat steps 6-10 until the end of the first list is reached.
- Return the count of common nodes.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *prev, *next;
};
void push(Node** head_ref, int new_data)
{
Node* new_node = (Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->prev = NULL;
new_node->next = (*head_ref);
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
(*head_ref) = new_node;
}
int countCommonNodes(Node** head_ref, Node** head)
{
Node* ptr = *head_ref;
Node* ptr1 = *head;
int count = 0;
while (ptr != NULL) {
while (ptr1 != NULL) {
if (ptr->data == ptr1->data) {
count++;
break ;
}
ptr1 = ptr1->next;
}
ptr1 = *head;
ptr = ptr->next;
}
return count;
}
int main()
{
Node* head = NULL;
Node* head1 = NULL;
push(&head, 17);
push(&head, 7);
push(&head, 6);
push(&head, 9);
push(&head, 10);
push(&head, 16);
push(&head, 15);
push(&head1, 6);
push(&head1, 9);
push(&head1, 45);
push(&head1, 16);
push(&head1, 15);
cout << "Number of common nodes:"
<< countCommonNodes(&head, &head1);
return 0;
}
|
Java
class GFG
{
static class Node
{
int data;
Node prev, next;
};
static Node push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.prev = null ;
new_node.next = head_ref;
if (head_ref != null )
head_ref.prev = new_node;
head_ref = new_node;
return head_ref;
}
static int countCommonNodes(Node head_ref,
Node head)
{
Node ptr = head_ref;
Node ptr1 = head;
int count = 0 ;
while (ptr != null )
{
while (ptr1 != null )
{
if (ptr.data == ptr1.data)
{
count++;
break ;
}
ptr1 = ptr1.next;
}
ptr1 = head;
ptr = ptr.next;
}
return count;
}
public static void main(String[] args)
{
Node head = null ;
Node head1 = null ;
head = push(head, 17 );
head = push(head, 7 );
head = push(head, 6 );
head = push(head, 9 );
head = push(head, 10 );
head = push(head, 16 );
head = push(head, 15 );
head1 = push(head1, 6 );
head1 = push(head1, 9 );
head1 = push(head1, 45 );
head1 = push(head1, 16 );
head1 = push(head1, 15 );
System.out.println( "Number of common nodes: " +
countCommonNodes(head, head1));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .prev = None
self . next = None
def push(head_ref, new_data):
new_node = Node(new_data)
new_node.data = new_data;
new_node.prev = None ;
new_node. next = (head_ref);
if ((head_ref) ! = None ):
(head_ref).prev = new_node;
(head_ref) = new_node;
return head_ref
def countCommonNodes(head_ref, head):
ptr = head_ref;
ptr1 = head;
count = 0 ;
while (ptr ! = None ):
while (ptr1 ! = None ):
if (ptr.data = = ptr1.data):
count + = 1
break ;
ptr1 = ptr1. next ;
ptr1 = head;
ptr = ptr. next ;
return count;
if __name__ = = '__main__' :
head = None ;
head1 = None ;
head = push(head, 17 );
head = push(head, 7 );
head = push(head, 6 );
head = push(head, 9 );
head = push(head, 10 );
head = push(head, 16 );
head = push( head, 15 );
head1 = push(head1, 6 );
head1 = push(head1, 9 );
head1 = push(head1, 45 );
head1 = push(head1, 16 );
head1 = push(head1, 15 );
print ( "Number of common nodes: " + str (countCommonNodes(head, head1)))
|
C#
using System;
class GFG
{
public class Node
{
public int data;
public Node prev, next;
};
static Node push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.prev = null ;
new_node.next = head_ref;
if (head_ref != null )
head_ref.prev = new_node;
head_ref = new_node;
return head_ref;
}
static int countCommonNodes(Node head_ref,
Node head)
{
Node ptr = head_ref;
Node ptr1 = head;
int count = 0;
while (ptr != null )
{
while (ptr1 != null )
{
if (ptr.data == ptr1.data)
{
count++;
break ;
}
ptr1 = ptr1.next;
}
ptr1 = head;
ptr = ptr.next;
}
return count;
}
public static void Main(String[] args)
{
Node head = null ;
Node head1 = null ;
head = push(head, 17);
head = push(head, 7);
head = push(head, 6);
head = push(head, 9);
head = push(head, 10);
head = push(head, 16);
head = push(head, 15);
head1 = push(head1, 6);
head1 = push(head1, 9);
head1 = push(head1, 45);
head1 = push(head1, 16);
head1 = push(head1, 15);
Console.WriteLine( "Number of common nodes: " +
countCommonNodes(head, head1));
}
}
|
Javascript
<script>
class Node {
constructor(val) {
this .data = val;
this .prev = null ;
this .next = null ;
}
}
function push(head_ref , new_data) {
var new_node = new Node();
new_node.data = new_data;
new_node.prev = null ;
new_node.next = head_ref;
if (head_ref != null )
head_ref.prev = new_node;
head_ref = new_node;
return head_ref;
}
function countCommonNodes(head_ref, head) {
var ptr = head_ref;
var ptr1 = head;
var count = 0;
while (ptr != null ) {
while (ptr1 != null ) {
if (ptr.data == ptr1.data) {
count++;
break ;
}
ptr1 = ptr1.next;
}
ptr1 = head;
ptr = ptr.next;
}
return count;
}
var head = null ;
var head1 = null ;
head = push(head, 17);
head = push(head, 7);
head = push(head, 6);
head = push(head, 9);
head = push(head, 10);
head = push(head, 16);
head = push(head, 15);
head1 = push(head1, 6);
head1 = push(head1, 9);
head1 = push(head1, 45);
head1 = push(head1, 16);
head1 = push(head1, 15);
document.write( "Number of common nodes: "
+ countCommonNodes(head, head1));
</script>
|
Output
Number of common nodes:4
Complexity Analysis:
- Time Complexity: O(n1*n2) where n1 is the length of the first linked list and n2 is the length of the second linked list
- Auxiliary Space: O(1)
Approach 2: Use hash tables or sets to keep track of the values in one list and then traverse the other list to count the common nodes.
Algorithm:
- Define a struct Node which consists of an integer data value, a pointer to the previous node, and a pointer to the next node.
- Create a push function to insert a new node at the beginning of the doubly linked list. This function takes the address of the head pointer and the new data as inputs.
- Create a countCommonNodes function to count the number of common nodes in two doubly linked lists. This function takes the addresses of the head pointers of both lists as inputs and returns an integer value.
- Inside the countCommonNodes function, initialize two node pointers ptr and ptr1 to the head of the first and second linked lists, respectively.
- Initialize a count variable to 0 to keep track of the number of common nodes.
- Traverse the first linked list using ptr and for each node of the first list, traverse the second linked list using ptr1.
- If the data value of the current node in the first list matches the data value of any node in the second list, increment the count variable and break the inner loop.
- After the inner loop completes, reset ptr1 to the head of the second list.
Move ptr to the next node of the first list and repeat steps 6-8 until ptr reaches the end of the first list.
- Return the count of common nodes.
- In the main function, create two doubly linked lists using push function and call the countCommonNodes function passing the head pointers of both the lists as inputs.
- Print the returned count value.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *prev, *next;
};
void push(Node** head_ref, int new_data)
{
Node* new_node = (Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->prev = NULL;
new_node->next = (*head_ref);
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
(*head_ref) = new_node;
}
int countCommonNodes(Node** head_ref, Node** head)
{
Node* ptr = *head_ref;
Node* ptr1 = *head;
int count = 0;
unordered_set< int > values;
while (ptr != NULL) {
values.insert(ptr->data);
ptr = ptr->next;
}
while (ptr1 != NULL) {
if (values.count(ptr1->data) > 0) {
count++;
}
ptr1 = ptr1->next;
}
return count;
}
int main()
{
Node* head = NULL;
Node* head1 = NULL;
push(&head, 17);
push(&head, 7);
push(&head, 6);
push(&head, 9);
push(&head, 10);
push(&head, 16);
push(&head, 15);
push(&head1, 6);
push(&head1, 9);
push(&head1, 45);
push(&head1, 16);
push(&head1, 15);
cout << "Number of common nodes:"
<< countCommonNodes(&head, &head1);
return 0;
}
|
Java
import java.util.HashSet;
class Node {
int data;
Node prev, next;
}
public class CommonNodeCount {
static void push(Node[] headRef, int newData)
{
Node newNode = new Node();
newNode.data = newData;
newNode.prev = null ;
newNode.next = headRef[ 0 ];
if (headRef[ 0 ] != null ) {
headRef[ 0 ].prev = newNode;
}
headRef[ 0 ] = newNode;
}
static int countCommonNodes(Node[] headRef, Node[] head)
{
Node ptr = headRef[ 0 ];
Node ptr1 = head[ 0 ];
int count = 0 ;
HashSet<Integer> values = new HashSet<>();
while (ptr != null ) {
values.add(ptr.data);
ptr = ptr.next;
}
while (ptr1 != null ) {
if (values.contains(ptr1.data)) {
count++;
}
ptr1 = ptr1.next;
}
return count;
}
public static void main(String[] args)
{
Node[] head = { null };
Node[] head1 = { null };
push(head, 17 );
push(head, 7 );
push(head, 6 );
push(head, 9 );
push(head, 10 );
push(head, 16 );
push(head, 15 );
push(head1, 6 );
push(head1, 9 );
push(head1, 45 );
push(head1, 16 );
push(head1, 15 );
System.out.println( "Number of common nodes: "
+ countCommonNodes(head, head1));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .prev = None
self . next = None
def push(head_ref, new_data):
new_node = Node(new_data)
new_node. next = head_ref
if head_ref ! = None :
head_ref.prev = new_node
head_ref = new_node
return head_ref
def countCommonNodes(head_ref, head):
ptr = head_ref
ptr1 = head
count = 0
values = set ()
while ptr ! = None :
values.add(ptr.data)
ptr = ptr. next
while ptr1 ! = None :
if ptr1.data in values:
count + = 1
ptr1 = ptr1. next
return count
if __name__ = = '__main__' :
head = None
head1 = None
head = push(head, 17 )
head = push(head, 7 )
head = push(head, 6 )
head = push(head, 9 )
head = push(head, 10 )
head = push(head, 16 )
head = push(head, 15 )
head1 = push(head1, 6 )
head1 = push(head1, 9 )
head1 = push(head1, 45 )
head1 = push(head1, 16 )
head1 = push(head1, 15 )
print ( "Number of common nodes:" ,
countCommonNodes(head, head1))
|
C#
using System;
using System.Collections.Generic;
public class Node {
public int data;
public Node prev, next;
}
class Program {
static void Push( ref Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.prev = null ;
new_node.next = head_ref;
if (head_ref != null )
head_ref.prev = new_node;
head_ref = new_node;
}
static int CountCommonNodes( ref Node head_ref,
ref Node head)
{
Node ptr = head_ref;
Node ptr1 = head;
int count = 0;
HashSet< int > values = new HashSet< int >();
while (ptr != null ) {
values.Add(ptr.data);
ptr = ptr.next;
}
while (ptr1 != null ) {
if (values.Contains(ptr1.data)) {
count++;
}
ptr1 = ptr1.next;
}
return count;
}
static void Main()
{
Node head = null ;
Node head1 = null ;
Push( ref head, 17);
Push( ref head, 7);
Push( ref head, 6);
Push( ref head, 9);
Push( ref head, 10);
Push( ref head, 16);
Push( ref head, 15);
Push( ref head1, 6);
Push( ref head1, 9);
Push( ref head1, 45);
Push( ref head1, 16);
Push( ref head1, 15);
Console.WriteLine(
"Number of common nodes: "
+ CountCommonNodes( ref head, ref head1));
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .prev = null ;
this .next = null ;
}
}
function push(head_ref, new_data) {
const new_node = new Node(new_data);
new_node.next = head_ref;
if (head_ref !== null ) {
head_ref.prev = new_node;
}
return new_node;
}
function GFG(head_ref, head) {
let count = 0;
const values = new Set();
let ptr = head_ref;
while (ptr !== null ) {
values.add(ptr.data);
ptr = ptr.next;
}
let ptr1 = head;
while (ptr1 !== null ) {
if (values.has(ptr1.data)) {
count++;
}
ptr1 = ptr1.next;
}
return count;
}
function main() {
let head = null ;
let head1 = null ;
head = push(head, 17);
head = push(head, 7);
head = push(head, 6);
head = push(head, 9);
head = push(head, 10);
head = push(head, 16);
head = push(head, 15);
head1 = push(head1, 6);
head1 = push(head1, 9);
head1 = push(head1, 45);
head1 = push(head1, 16);
head1 = push(head1, 15);
const commonNodeCount = GFG(head, head1);
console.log( "Number of common nodes: " + commonNodeCount);
}
main();
|
Output:
Number of common nodes:4
Time complexity: O(m*n)
The time complexity of the code is O(mn), where m and n are the sizes of the two input linked lists. This is because we have to traverse both linked lists completely to find common nodes. The nested while loop inside the function iterates over each node of the second list for each node of the first list. This results in a time complexity of O(mn).
Auxiliary space: O(1)
The auxiliary space complexity of the code is O(1) because we are not using any extra space for storing information. We are just using pointers to traverse the linked lists and an integer variable to store the count of common nodes. Therefore, the space complexity remains constant, i.e., O(1).
Similar Reads
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 -
15+ min read
First common element in two linked lists
Given two Linked Lists, find the first common element between given linked list i.e., we need to find first node of the first list which is also present in the second list. Examples: Input : List1: 10->15->4->20 Lsit2: 8->4->2->10 Output : 10 Input : List1: 1->2->3->4 Lsit
6 min read
Find common elements in three linked lists
Given three linked lists, find all common elements among the three linked lists. Examples: Input : 10 15 20 25 12 10 12 13 15 10 12 15 24 25 26 Output : 10 12 15 Input : 1 2 3 4 5 1 2 3 4 6 9 8 1 2 4 5 10 Output : 1 2 4 Method 1 : (Simple) Use three-pointers to iterate the given three linked lists a
11 min read
Remove the common nodes in two Singly Linked Lists
Given two Linked Lists L1 and L2, the task is to generate a new linked list with no common elements from the given two linked lists. Example: Input: L1 = 10 -> 15 -> 5 -> 20, L2 = 8 -> 5 -> 20 -> 10 Output: 8 -> 15 Explanation: Since both the linked list has 5, 10 and 20 in comm
10 min read
Concatenation of two Linked lists
Given two linked lists. The task is to concatenate the second list to the end of the first list. Examples: Input: list1: 10 -> 15 -> 4 -> 20, list2: 8 -> 4 -> 2 -> 10Output: 10 -> 15 -> 4 -> 20 -> 8 -> 4 -> 2 -> 10 Input: list1: 1 -> 2 -> 3, list2: 4 -
7 min read
Insert a Node at a specific position in Doubly Linked List
Given a Doubly Linked List, the task is to insert a new node at a specific position in the linked list. Â Examples: Input: Linked List = 1 <-> 2 <-> 4, newData = 3, position = 3Output: Linked List = 1 <-> 2 <-> 3 <-> 4Explanation: New node with data = 3 is inserted at po
13 min read
Find extra node in the second Linked list
Given two Linked list L1 and L2. The second list L2 contains all the nodes of L1 along with 1 extra node. The task is to find that extra node. Examples: Input: L1 = 17 -> 7 -> 6 -> 16 L2 = 17 -> 7 -> 6 -> 16 -> 15 Output: 15 Explanation: Element 15 is not present in the L1 listI
7 min read
Longest common suffix of two linked lists
Given two singly linked lists, find the Longest common suffix of two linked lists. If there are no common characters which are suffixes, return the minimum length of the two linked lists. Examples: Input : list1 = w -> a -> l -> k -> i -> n -> g list2 = l -> i -> s -> t -
12 min read
Swap given nodes in a Doubly Linked List without modifying data
Given a doubly linked list having all unique elements and two keys X and Y, the task is to swap nodes for two given keys by changing links only. Note: It may be considered that X and Y are always present in the list. Examples: Input: list = 1 <-> 8 <-> 7 <-> 9 <-> 4, X = 1, Y
11 min read
Insert a Node after a given node in Doubly Linked List
Given a Doubly Linked List, the task is to insert a new node after a given node in the linked list. Examples: Input: Linked List = 1 <-> 2 <-> 4, newData = 3, key = 2Output: Linked List = 1 <-> 2 <-> 3 <-> 4Explanation: New node 3 is inserted after key, that is node 2.
11 min read