- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the common nodes in two singly linked list in C++
Suppose we have two singly-linked lists. We have to find the total number of common nodes in both the singly 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
#include<iostream> using namespace std; class Node { public: int data; Node *next; }; void prepend(Node** start, int new_data) { Node* new_node = new Node; new_node->data = new_data; new_node->next = NULL; if ((*start) != NULL){ new_node->next = (*start); *start = 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->next; } ptr1 = *start2; ptr = ptr->next; } return count; } int main() { Node* first = NULL; Node* second = NULL; prepend(&first, 15); prepend(&first, 16); prepend(&first, 10); prepend(&first, 9); prepend(&first, 7); prepend(&first, 17); prepend(&second, 15); prepend(&second, 16); prepend(&second, 40); prepend(&second, 6); prepend(&second, 9); cout << "Number of common nodes:" << countCommonNodes(&first, &second); }
Output
Number of common nodes:3
- Related Articles
- Reverse Alternate K Nodes in a Singly Linked List in C++
- Sum of the nodes of a Singly Linked List in C Program
- Delete all Prime Nodes from a Singly Linked List in C++
- Alternate Odd and Even Nodes in a Singly Linked List in C++
- Product of all prime nodes in a Singly Linked List in C++
- Product of the nodes of a Singly Linked List
- Delete all Non-Prime Nodes from a Singly Linked List in C++
- Find count of common nodes in two Doubly Linked Lists in C++
- Find middle of singly linked list Recursively in C++
- Convert singly linked list into circular linked list in C++
- Convert singly linked list into XOR linked list in C++
- Find smallest and largest elements in singly linked list in C++
- Binary Search on Singly Linked List in C++
- Find minimum and maximum elements in singly Circular Linked List in C++
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes in Python

Advertisements