#include <stdio.h>
#define NULL 0
typedef struct pnode
{
int exp,coef;
struct pnode *next;
}pnode;
int createpolyn(pnode *h)
{
pnode *p,*q;
int i,num,a,b;
h=(pnode *)malloc(sizeof(pnode));
if(!h)
return(0);
h->next=NULL;
printf("\nplease input the number of item of the polynomial you want to creat:\n");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
printf("\nplease input the exp & coef of NO.%d item:\n",num-i+1);
p=(pnode *)malloc(sizeof(pnode));
if(p==NULL)
return(0);
scanf("%d,%d",&a,&b);printf("%d\n",p);
p->exp=a;
p->coef=b;
p->next=h->next;
h->next=p;
}
return(1);
}
void outputpolyn(pnode *h)
{
pnode *p;
p=h->next;
while(p!=NULL)
{ printf("%d",p);
printf("(%d,%d) ",p->exp,p->coef);
p=p->next;
}
}
pnode* addpolyn(pnode *ha,pnode *hb)
{
pnode *pa,*pb,*p,*s,*q;
int sum;
pa=ha->next;
pb=hb->next;
p=hb;
while(pa!=NULL&&pb!=NULL)
{
if(pb->exp > pa->exp)
{
p=pb;
pb=pb->next;
}
else if(pb->exp < pa->exp)
{
s=pa;
pa=pa->next;
s->next=pb;
p->next=s;
p=s;
}
else{
sum=pb->coef+pa->coef;
if(sum==NULL)
{
s=pa;
pa=pa->next;
q=pb;
pb=pb->next;
p->next=pb;
free(s);
free(q);
}
else{
s=pa;
pa=pa->next;
pb->coef=sum;
free(s);
}
}
}
if(pa!=NULL)
p->next=pa;
free(ha);
return(hb);
}
main()
{
pnode *ha,*hb,*hc;
createpolyn(ha);
outputpolyn(ha);
createpolyn(hb);
outputpolyn(hb);
hc=addpolyn(ha,hb);
outputpolyn(hc);
}