#include
#include
#include
typedef struct polynode
{
float coef;
int exp;
struct polynode *next;
}polynode,*PLinklist;
PLinklist Create(int n)
{
PLinklist L,p;
int i;
L = (PLinklist)malloc(sizeof(polynode));
L->next = NULL;
for(i=n; i>0 ;--i)
{
p = (PLinklist)malloc(sizeof(polynode));
scanf("%f%d",&p->coef,&p->exp);
p->next = L->next;
L->next = p;
}
return(L);
}
PLinklist Attach(float co,int ex,PLinklist o)
{
PLinklist c;
c = (PLinklist)malloc(sizeof(polynode));
c->coef = co;
c->exp = ex;
o->next = c;
return c;
}
void Print(PLinklist L)
{
int i = 0;
PLinklist p = L;
while(p->next != NULL)
{
i++;
printf("%fx^%d ",p->coef,p->exp);
p=p->next;
}
printf("\n");
}
PLinklist Add(PLinklist A,PLinklist B)
{
PLinklist C;
PLinklist o;
PLinklist p = A;
PLinklist q = B;
float sum;
C = (PLinklist)malloc(sizeof(polynode));
o=C;
while((p != NULL) && (q != NULL))
{
if(p->exp == q->exp)
{
sum = p->coef+q->coef;
if(sum != 0)
o = Attach(sum,p->exp,o);
p = p->next;
q = q->next;
}
else if(p->exp < q->exp)
{
o = Attach(q->coef,q->exp,o);
q = q->next;
}
else{
o = Attach(p->coef,p->exp,o);
p = p->next;
}
}
while(p != NULL)
{
o = Attach(p->coef,p->exp,o);
p = p->next;
}
while(q != NULL)
{
o = Attach(q->coef,q->exp,o);
q = q->next;
}
o->next = NULL;
p = C;
C = C->next;
return C;
}
void main()
{
int n;
PLinklist A, B, C;
printf("Input the length of A :\n");
scanf("%d",&n);
A = Create(n);
Print(A);
printf("Input the length of B :\n");
scanf("%d",&n);
B = Create(n);
Print(B);
C = Add(A,B);
Print(C);
}