#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct poly {
double coef;
int exp;
struct poly * link;
};
typedef struct poly * polyptr;
polyptr read_poly();
polyptr insert_end(polyptr first, double coef, int exp);
void write_poly(polyptr first);
polyptr addpoly(polyptr p1, polyptr p2);
int main() {
polyptr p1, p2, p3;
p1 = read_poly();
printf("\nConstructed polynomial in the form of linked lists\n");
write_poly(p1);
p2 = read_poly();
printf("\nConstructed polynomial in the form of linked lists\n");
write_poly(p2);
p3 = addpoly(p1, p2);
printf("\nAdded polynomial in the form of linked lists\n");
write_poly(p3);
}
polyptr insert_end(polyptr first, double coef, int exp) {
polyptr p, t;
p = (polyptr) malloc(sizeof(struct poly));
if (p == NULL) {
printf("no space available");
exit(1);
}
p -> coef = coef;
p -> exp = exp;
p -> link = NULL;
if (first == NULL) {
return p;
}
t = first;
while (t -> link != NULL)
t = t -> link;
t -> link = p;
return first;
}
polyptr read_poly() {
polyptr first = NULL;
double c;
int p;
printf("Enter the coef&exp in decreasing order of exponent(terminate with 0,0)\n");
scanf("%lf%d", & c, & p);
while (c != 0) {
first = insert_end(first, c, p);
printf("Enter the coef and exp(terminate with 0,0)\n");
scanf("%lf%d", & c, & p);
}
return first;
}
void write_poly(polyptr first) {
polyptr t;
if (first == NULL)
return;
t = first;
while (t -> link != NULL) {
printf("(%lf)*x^%ld+", t -> coef, t -> exp);
t = t -> link;
}
printf("(%lf)*x^%ld\n", t -> coef, t -> exp);
}
polyptr addpoly(polyptr p1, polyptr p2) {
polyptr temp = NULL;
double c;
while (p1 != NULL && p2 != NULL) {
if (p1 -> exp > p2 -> exp) {
temp = insert_end(temp, p1 -> coef, p1 -> exp);
p1 = p1 -> link;
} else if (p1 -> exp < p2 -> exp) {
temp = insert_end(temp, p2 -> coef, p2 -> exp);
p2 = p2 -> link;
} else {
c = p1 -> coef + p2 -> coef;
temp = insert_end(temp, c, p2 -> exp);
p1 = p1 -> link;
p2 = p2 -> link;
}
}
while (p1 != NULL) {
temp = insert_end(temp, p1 -> coef, p1 -> coef);
p1 = p1 -> link;
}
while (p2 != NULL) {
temp = insert_end(temp, p2 -> coef, p2 -> coef);
p2 = p2 -> link;
}
return temp;
}
Note: Need to be arranged in compiler after copied
OutPut:
Enter the coef&exp in decreasing order of exponent(terminate with 0,0)
5 3
Enter the coef and exp(terminate with 0,0)
6 2
Enter the coef and exp(terminate with 0,0)
7 1
Enter the coef and exp(terminate with 0,0)
8 0
Enter the coef and exp(terminate with 0,0)
0 0
Constructed polynomial in the form of linked lists
(5)x^3+(6)x^2+(7)x^1+(8)x^0
Enter the coef&exp in decreasing order of exponent(terminate with 0,0)
4 2
Enter the coef and exp(terminate with 0,0)
3 1
Enter the coef and exp(terminate with 0,0)
2 0
Enter the coef and exp(terminate with 0,0)
0 0
Constructed polynomial in the form of linked lists
(4)x^2+(3)x^1+(2)x^0
Added polynomial in the form of linked lists
(5)x^3+(10)x^2+(10)x^1+(10)x^0