//Addition of two polynomials.
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int exp, coef;
struct node *next;
}P;
void create(P *p1);
void display(P *p1);
void add(P *p1, P *p2, P *p3);
void main()
{
P *p1, *p2, *p3, *p4;
p1=(P*)malloc(sizeof(P));
p1->next=NULL;
p2=(P*)malloc(sizeof(P));
p2->next=NULL;
p3=(P*)malloc(sizeof(P));
p3->next=NULL;
p4=(P*)malloc(sizeof(P));
p4->next=NULL;
create(p1);
printf("1st Polynomial is:\t");
display(p1);
printf("\n\n");
create(p2);
printf("2nd Polynomial is:\t");
display(p2);
printf("\n\n");
add(p1, p2, p3);
printf("\n Addition of 1st and 2nd Polynomial is:\n");
display(p1);
printf("+");
display(p2);
printf("=");
display(p3);
printf("\n\n");
}
void create(P *p1)
{
P *temp=p1, *nn;
int i, n;
printf("How many terms you want to enter:");
scanf("%d", &n);
printf(">>>Enter terms in desending order of power<<<\n");
for(i=0; i<n; i++)
{
nn=(P*)malloc(sizeof(P));
nn->next=NULL;
printf("Enter coefficient of the term: %d=", i+1);
scanf("%d", &nn->coef);
printf("Enter exponetial of the term:%d=", i+1);
scanf("%d", &nn->exp);
if(p1==NULL)
p1=temp=nn;
temp->next=nn;
temp=nn;
}
}
void display(P *p1)
{
P *temp;
for(temp=p1->next;temp!=NULL; temp=temp->next)
printf("[%d^%d]+",temp->coef, temp->exp);
printf("\b");
}
void add(P *p1, P *p2, P *p3)
{
P *t1=p1->next, *t2=p2->next, *t3=p3, *nn;
int i;
while(t1 && t2)
{
nn=(P*)malloc(sizeof(P));
nn->next=NULL;
if(t1->exp > t2->exp)
{
nn->exp=t1->exp;
nn->coef=t1->coef;
t1=t1->next;
}
else
if(t1->exp < t2->exp)
{
nn->exp=t2->exp;
nn->coef=t2->coef;
t2=t2->next;
}
else
if(t1->exp==t2->exp)
{
nn->exp=t2->exp;
nn->coef=t1->coef+t2->coef;
t1=t1->next;
t2=t2->next;
}
t3->next=nn;
t3=nn;
}
while(t1)
{
nn=(P*)malloc(sizeof(P));
nn->next=NULL;
nn->exp=t1->exp;
nn->coef=t1->coef;
t3->next=nn;
t3=nn;
t1=t1->next;
}
while(t2)
{
nn=(P*)malloc(sizeof(P));
nn->next=NULL;
nn->next=NULL;
nn->exp=t2->exp;
nn->coef=t2->coef;
t3->next=nn;
t3=nn;
t2=t2->next;
}
}