Skip to content

Instantly share code, notes, and snippets.

@shivajichalise
Last active January 27, 2022 08:04
Show Gist options
  • Save shivajichalise/87e8faf256f34649d6e30e4c2fd064e9 to your computer and use it in GitHub Desktop.
Save shivajichalise/87e8faf256f34649d6e30e4c2fd064e9 to your computer and use it in GitHub Desktop.
Add two polynomials using linked list in C++
#include <iostream>
using namespace std;
class Node {
public:
int coeff;
int power;
Node *next;
};
void create_node(int x, int y, Node **temp) {
Node *a, *r;
a = *temp;
if (a == NULL) {
r = new Node;
r->coeff = x;
r->power = y;
*temp = r;
r->next = new Node;
r = r->next;
r->next = NULL;
} else {
r->coeff = x;
r->power = y;
r->next = new Node;
r = r->next;
r->next = NULL;
}
}
void add(Node *p1, Node *p2, Node *result) {
while (p1->next && p2->next) {
if (p1->power > p2->power) {
result->power = p1->power;
result->coeff = p1->coeff;
p1 = p1->next;
} else if (p1->power < p2->power) {
result->power = p2->power;
result->coeff = p2->coeff;
p2 = p2->next;
} else {
result->power = p1->power;
result->coeff = p1->coeff + p2->coeff;
p1 = p1->next;
p2 = p2->next;
}
result->next = new Node;
result = result->next;
result->next = NULL;
}
while (p1->next || p2->next) {
if (p1->next) {
result->power = p1->power;
result->coeff = p1->coeff;
p1 = p1->next;
}
if (p2->next) {
result->power = p2->power;
result->coeff = p2->coeff;
p2 = p2->next;
}
result->next = new Node;
result = result->next;
result->next = NULL;
}
}
// display function to print resultant polynomial
void display(Node *node) {
while (node->next != NULL) {
cout << node->coeff << "x^" << node->power;
node = node->next;
if (node->next != NULL)
cout << " + ";
}
cout << endl;
}
int main() {
Node *p1 = NULL, *p2 = NULL, *result = NULL;
// creating polynomial1 p1 and polynomial2 p2
create_node(4, 5, &p1);
create_node(2, 3, &p1);
create_node(5, 0, &p1);
create_node(2, 3, &p2);
create_node(5, 2, &p2);
create_node(5, 1, &p2);
cout << "polynomial 1: ";
display(p1);
cout << endl << "polynomial 2: ";
display(p2);
result = new Node;
add(p1, p2, result);
cout << endl << "resultant polynomial: ";
display(result);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment