6-9-Multiplication of Two Polynomials Using Linked List
6-9-Multiplication of Two Polynomials Using Linked List
Given two polynomials in the form of a linked list, the task is to perform the multiplication of both polynomials.
Examples:
Approach:
The idea is to traverse the second list for each node in the first list, calculate the product of coefficients
and sum of powers, and store the results in a map where the key represents the power and the value
represents the coefficient. Finally, traverse the map to create new nodes for the resulting polynomial, link
them, and return the head of the resultant list.
1
// C++ Program to multiply two polynomials
2
// represented as linked lists
3
#include <bits/stdc++.h>
4
using namespace std;
6
class Node {
7
public:
8
int coeff, power;
9
Node *next;
10
Node(int p, int c) {
11
power = p;
12
coeff = c;
13
next = nullptr;
14
}
15
};
16
17
Node *multiplyPolynomials(Node *poly1, Node *poly2) {
18
19
map<int, int> resultMap;
20
21
// Multiply each node of poly2 with poly1
22
for (Node *curr1 = poly1; curr1 != nullptr; curr1 = curr1->next) {
23
for (Node *curr2 = poly2; curr2 != nullptr; curr2 = curr2->next) {
24
int power = curr1->power + curr2->power;
25
int coeff = curr1->coeff * curr2->coeff;
26
resultMap[power] += coeff;
27
}
28
}
29