দুটি লিঙ্কড লিস্টে অঙ্কগুলো থাকে। লিস্ট দুটি থেকে সংখ্যা বানিয়ে তাদের গুণফল বের করতে হবে।
উদাহরণ
ইনপুট: 1→2→NULL এবং 2→3→NULL
আউটপুট: 2→7→6→NULL (১২ × ২৩ = ২৭৬)
অ্যালগরিদম
- দুটি লিস্ট ট্রাভার্স করে সংখ্যা দুটি বানান (
num = num * 10 + digit)। - দুটি সংখ্যা গুণ করুন।
- গুণফল থেকে নতুন লিস্ট তৈরি করুন (পিছন থেকে অঙ্ক নিয়ে)।
সি++ ইমপ্লিমেন্টেশন
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
void addNewNode(Node** head, int data) {
Node* newNode = new Node{data, *head};
*head = newNode;
}
void multiplyTwoLinkedLists(Node* first, Node* second, Node** result) {
long long num1 = 0, num2 = 0;
while (first || second) {
if (first) { num1 = num1 * 10 + first->data; first = first->next; }
if (second) { num2 = num2 * 10 + second->data; second = second->next; }
}
long long product = num1 * num2;
while (product) {
addNewNode(result, product % 10);
product /= 10;
}
}
void printList(Node* node) {
while (node) { cout << node->data << "->"; node = node->next; }
cout << "NULL" << endl;
}
int main() {
Node *first = nullptr, *second = nullptr;
addNewNode(&first, 1); addNewNode(&first, 2); addNewNode(&first, 3);
addNewNode(&second, 1); addNewNode(&second, 2);
printList(first); // 3->2->1->NULL
printList(second); // 2->1->NULL
Node* result = nullptr;
multiplyTwoLinkedLists(first, second, &result);
printList(result); // 6->7->4->1->NULL (১২৩ × ১২ = ১৪৭৬)
return 0;
}
আউটপুট
3->2->1->NULL 2->1->NULL 6->7->4->1->NULL