# Multiply two polynomials using linked list in node js

Js program for Multiply two polynomials using linked list. Here problem description and explanation.

``````/*
Node JS program for
Multiplication of two polynomials using linked list
*/
class Node
{
constructor(data, power)
{
this.data = data;
this.power = power;
this.next = null;
}
// Update node value
updateRecord(data, power)
{
this.data = data;
this.power = power;
}
}
class MultiplyPolynomial
{
constructor()
{
}
// Insert Node element
insert(data, power)
{
{
}
else
{
var node = null;
var location = null;
// Find the valid new node location
while (temp != null && temp.power >= power)
{
location = temp;
temp = temp.next;
}
if (location != null && location.power == power)
{
// When polynomial power already exists
location.data = location.data + data;
}
else
{
node = new Node(data, power);
if (location == null)
{
// When add node in begining
}
else
{
// When adding node in intermediate
// location or end location
node.next = location.next;
location.next = node;
}
}
}
}
// Perform multiplication of given polynomial
multiplyPolynomials(other)
{
// Define some useful variable
var result = new MultiplyPolynomial();
// Get first node of polynomial
var power_value = 0;
var coefficient = 0;
// Execute loop until when polynomial are exist
while (poly1 != null)
{
while (temp != null)
{
// Get result info
power_value = poly1.power + temp.power;
coefficient = poly1.data * temp.data;
result.insert(coefficient, power_value);
// Visit to next node
temp = temp.next;
}
// Visit to next node
poly1 = poly1.next;
}
// return first node
return result;
}
// Display given polynomial nodes
display()
{
{
process.stdout.write("Empty Polynomial ");
}
process.stdout.write(" ");
while (temp != null)
{
{
process.stdout.write(" + " + temp.data);
}
else
{
process.stdout.write("" + temp.data);
}
if (temp.power != 0)
{
process.stdout.write("x^" + temp.power);
}
// Visit to next node
temp = temp.next;
}
process.stdout.write("\n");
}
}

function main()
{
var a = new MultiplyPolynomial();
var b = new MultiplyPolynomial();
// Add node in polynomial A
a.insert(9, 3);
a.insert(4, 2);
a.insert(3, 0);
a.insert(7, 1);
a.insert(3, 4);
// Add node in polynomial b
b.insert(7, 3);
b.insert(4, 0);
b.insert(6, 1);
b.insert(1, 2);
// Display Polynomial nodes
console.log("\n Polynomial A ");
a.display();
console.log(" Polynomial B ");
b.display();
var result = a.multiplyPolynomials(b);
// Display calculated result
console.log(" Result ");
result.display();
}
// Start program execution
main();``````

Output

`````` Polynomial A
3x^4 + 9x^3 + 4x^2 + 7x^1 + 3
Polynomial B
7x^3 + 1x^2 + 6x^1 + 4
Result
21x^7 + 66x^6 + 55x^5 + 119x^4 + 88x^3 + 61x^2 + 46x^1 + 12``````

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.