Dsu 15
Dsu 15
Code :
#include <stdio.h> }
#include <stdlib.h> if (temp->exp == exp) {
struct PolyNode { temp->coeff += coeff;
int coeff; } else {
int exp; newNode->next = temp-
>next;
struct PolyNode* next;
temp->next = newNode;
};
}
struct PolyNode* createNode(int
coeff, int exp) { }
struct PolyNode* newNode = }
(struct
void displayPolynomial(struct
PolyNode*)malloc(sizeof(struct
PolyNode* poly) {
PolyNode));
struct PolyNode* temp = poly;
newNode->coeff = coeff;
while (temp != NULL) {
newNode->exp = exp;
printf("%dx^%d", temp->coeff,
newNode->next = NULL;
temp->exp);
return newNode;
if (temp->next != NULL &&
} temp->next->coeff > 0) {
void insertTerm(struct PolyNode** printf(" + ");
poly, int coeff, int exp) {
}
struct PolyNode* newNode =
temp = temp->next;
createNode(coeff, exp);
}
if (*poly == NULL || (*poly)->exp
< exp) { printf("\n");
newNode->next = *poly; }
*poly = newNode; struct PolyNode*
addPolynomials(struct PolyNode*
} else {
poly1, struct PolyNode* poly2) {
struct PolyNode* temp = *poly;
struct PolyNode* result = NULL;
while (temp->next != NULL &&
struct PolyNode* p1 = poly1;
temp->next->exp > exp) {
struct PolyNode* p2 = poly2;
temp = temp->next;
while (p1 != NULL && p2 != NULL) struct PolyNode* poly2 = NULL;
{
struct PolyNode* result = NULL;
if (p1->exp > p2->exp) {
printf("Enter terms for first
insertTerm(&result, p1- polynomial (coeff exp). Enter 0 0 to
>coeff, p1->exp); end.\n");
p1 = p1->next; int coeff, exp;
} else if (p1->exp < p2->exp) { while (1) {
insertTerm(&result, p2- printf("Enter coefficient and
>coeff, p2->exp); exponent: ");
p2 = p2->next; scanf("%d %d", &coeff, &exp);
} else { if (coeff == 0 && exp == 0)
break;
insertTerm(&result, p1->coeff
+ p2->coeff, p1->exp); insertTerm(&poly1, coeff, exp);
p1 = p1->next; }
p2 = p2->next; printf("Enter terms for second
polynomial (coeff exp). Enter 0 0 to
}
end.\n");
}
while (1) {
while (p1 != NULL) {
printf("Enter coefficient and
insertTerm(&result, p1->coeff, exponent: ");
p1->exp);
scanf("%d %d", &coeff, &exp);
p1 = p1->next;
if (coeff == 0 && exp == 0)
} break;
insertTerm(&result, p2->coeff, }
p2->exp);
p2 = p2->next;
result = addPolynomials(poly1,
} poly2);
} displayPolynomial(result);
OUTPUT :