0% found this document useful (0 votes)
5 views

Add Two Polynomial

dsa program

Uploaded by

helloaiai8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Add Two Polynomial

dsa program

Uploaded by

helloaiai8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdlib.h>
struct Node {
int coeff;
int pow;
struct Node* next;
};
struct Node* createNode(int coeff, int pow) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->coeff = coeff;
newNode->pow = pow;
newNode->next = NULL;
return newNode;
}
struct Node* addPolynomials(struct Node* poly1, struct Node* poly2) {
struct Node* result = NULL;
struct Node** tail = &result;
while (poly1 || poly2) {
if (poly1 && (!poly2 || poly1->pow > poly2->pow)) {
*tail = createNode(poly1->coeff, poly1->pow);
poly1 = poly1->next;
} else if (poly2 && (!poly1 || poly1->pow < poly2->pow)) {
*tail = createNode(poly2->coeff, poly2->pow);
poly2 = poly2->next;
} else {
*tail = createNode(poly1->coeff + poly2->coeff, poly1->pow);
poly1 = poly1->next;
poly2 = poly2->next;
}
tail = &((*tail)->next);
}
return result;
}
void printPolynomial(struct Node* poly) {
while (poly) {
printf("%dx^%d", poly->coeff, poly->pow);
poly = poly->next;
if (poly) printf(" + ");
}
printf("\n");
}
int main() {
struct Node* poly1 = createNode(3, 3);
poly1->next = createNode(5, 2);
struct Node* poly2 = createNode(4, 2);
poly2->next = createNode(2, 1);
poly2->next->next = createNode(1, 0);
printf("First polynomial: ");
printPolynomial(poly1);
printf("Second polynomial: ");
printPolynomial(poly2);
struct Node* sum = addPolynomials(poly1, poly2);
printf("Sum of polynomials: ");
printPolynomial(sum);
return 0;
}

OUTPUT:

You might also like