#include<stdio.h>
#include<stdlib.h>
typedef struct poly {
int coff, powr;
struct poly * next;
}
pl;
pl* creatpoly();
pl* addpoly(pl * , pl * );
void display(pl * );
void main() {
int n;
pl * pl1, * pl2, * pl3;
pl1 = pl2 = pl3 = NULL;
printf("\n Enter 1st Polynomial : ");
pl1=creatpoly( );
printf("\n Enter 2nd Polynomial : ");
pl2=creatpoly( );
printf("\n\n First Polynomial : ");
display(pl1);
printf("\n\n Second Polynomial : ");
display(pl2);
printf("\n\n After Addition Resulatnt Polynomial : ");
pl3=addpoly(pl1, pl2);
display(pl3);
}
pl* creatpoly() {
int cof, powe, temp = 10;
char ch;
pl *head=NULL,*ptr,*tmp, *t1;
while (1) {
printf("\n Enter Coff of X : ");
scanf("%d", & cof);
printf("\n Enter Powr of X : ");
scanf("%d", & powe);
if (powe < temp)
{
tmp = (pl * ) malloc(sizeof(pl));
tmp -> coff = cof;
tmp -> powr = powe;
tmp -> next = NULL;
if ( head == NULL) {
head = tmp;
} else {
t1 -> next = tmp;
}
t1=tmp;
}
else {
printf("\n Power must be lesser than the previous term :");
continue;
}
temp = powe;
printf("\n Do you have more nodes?(y/n): ");
fflush(stdin);
scanf(" %c", & ch);
if (ch == 'n' || ch == 'N')
break;
}
return head;
}
pl* addpoly(pl * ptr1, pl * ptr2 ) {
pl *p3, * temp,*ptr3=NULL;
while (ptr1 != NULL && ptr2 != NULL) {
if ((ptr1 -> powr) > (ptr2 -> powr)) {
p3 = ptr1;
ptr1 = ptr1 -> next;
} else if (ptr1 -> powr < ptr2 -> powr) {
p3 = ptr2;
ptr2 = ptr2 -> next;
} else {
ptr1 -> coff = ptr1 -> coff + ptr2 -> coff;
p3 = ptr1;
ptr1 = ptr1 -> next;
ptr2 = ptr2 -> next;
}
if ( ptr3 == NULL)
ptr3 = p3;
else
temp -> next = p3;
temp = p3;
}
if (ptr1 == NULL && ptr2 != NULL)
temp -> next = ptr2;
if (ptr1 != NULL && ptr2 == NULL)
temp -> next = ptr1;
return ptr3;
}
void display(pl * h) {
while (h -> next != NULL) {
printf("%dx^%d+", h -> coff, h -> powr);
h = h -> next;
}
printf("%dx^%d", h -> coff, h -> powr);
}