Find count of common nodes in two Doubly Linked Lists in C++

Suppose we have two doubly-linked lists. We have to find the total number of common nodes in both the doubly linked list. So if two lists are like [15, 16, 10, 9, 7, 17], and [15, 16, 40, 6, 9], there are three common nodes.

Traverse both lists up to end of the list using two nested loops, for every node in the list, check if it is matched with any node of the second list or not. If a match is found, then increase the counter, and finally return the count.

Example

Live Demo

#include<iostream>
using namespace std;
class Node {
public:
int data;
Node *back, *front;
};
void append(Node** start, int new_data) {
Node* new_node = new Node;
new_node->data = new_data;
new_node->back = NULL;
new_node->front = (*start);
if ((*start) != NULL)
(*start)->back = new_node;
(*start) = new_node;
}
int countCommonNodes(Node** start1, Node** start2) {
Node* ptr = *start1;
Node* ptr1 = *start2;
int count = 0;
while (ptr != NULL) {
while (ptr1 != NULL) {
if (ptr->data == ptr1->data) {
count++;
break;
}
ptr1 = ptr1->front;
}
ptr1 = *start2;
ptr = ptr->front;
}
return count;
}
int main() {
Node* first = NULL;
Node* second = NULL;
append(&first, 15);
append(&first, 16);
append(&first, 10);
append(&first, 9);
append(&first, 7);
append(&first, 17);
append(&second, 15);
append(&second, 16);
append(&second, 40);
append(&second, 6);
append(&second, 9);
cout << "Number of common nodes:" << countCommonNodes(&first, &second);
}

Output

Number of common nodes:3

Updated on: 19-Dec-2019

202 Views