তিনটি লিঙ্কড লিস্ট দেওয়া থাকলে, প্রতিটি লিস্ট থেকে এক করে নোড নিয়ে যোগফল দেওয়া সংখ্যার সমান হয় এমন ট্রিপলেট বের করতে হবে।
পদ্ধতি
- লিঙ্কড লিস্ট নোড স্ট্রাকচার ও ইনসার্ট ফাংশন তৈরি করুন।
- তিনটি নেস্টেড লুপ দিয়ে তিনটি লিস্টের সব সম্ভাব্য কম্বিনেশন চেক করুন।
- যোগফল মিললে প্রিন্ট করুন এবং লুপ ব্রেক করুন।
উদাহরণ
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data; Node* next;
};
void insert(Node** head, int data) {
Node* n = new Node();
n->data = data; n->next = *head; *head = n;
}
void findTriplet(Node* h1, Node* h2, Node* h3, int target) {
bool found = false;
for (Node* a = h1; a && !found; a = a->next)
for (Node* b = h2; b && !found; b = b->next)
for (Node* c = h3; c; c = c->next)
if (a->data + b->data + c->data == target) {
cout << a->data << " " << b->data << " " << c->data << endl;
found = true; break;
}
if (!found) cout << "No triplet found" << endl;
}
int main() {
Node *h1=NULL, *h2=NULL, *h3=NULL;
insert(&h1,4); insert(&h1,3); insert(&h1,2); insert(&h1,1);
insert(&h2,4); insert(&h2,3); insert(&h2,2); insert(&h2,1);
insert(&h3,1); insert(&h3,2); insert(&h3,3); insert(&h3,4);
findTriplet(h1,h2,h3,9);
findTriplet(h1,h2,h3,100);
return 0;
}
আউটপুট
1 4 4 No triplet found