দুটি সিঙ্গলি লিঙ্কড লিস্ট দেওয়া আছে। উভয় লিস্টে কমন নোডের সংখ্যা বের করতে হবে। উদাহরণ: [15,16,10,9,7,17] এবং [15,16,40,6,9] -> ৩টি কমন নোড।
নেস্টেড লুপ দিয়ে প্রতিটি নোড দ্বিতীয় লিস্টে খুঁজুন। মিল পেলে কাউন্ট বাড়ান।
উদাহরণ
#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 = *start;
*start = new_node;
}
int countCommonNodes(Node** start1, Node** start2) {
int count = 0;
for (Node* p = *start1; p; p = p->next) {
for (Node* q = *start2; q; q = q->next) {
if (p->data == q->data) { count++; break; }
}
}
return count;
}
int main() {
Node *first = NULL, *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);
return 0;
}
আউটপুট
Number of common nodes: 3