用链表实现多项式相加
各位大哥大姐,请帮忙看看我的这个程序那有错误!!!!急用#define NULL 0
struct term
{int coef;
int expn;
struct term *next;
};
int n;
struct term *creat(void)
{struct term *La;
struct term *p1,*p2;
n=0;
p1=p2=(struct term *)malloc(sizeof(struct term));
scanf("%d,%d",&p1->coef,&p1->expn);
La=NULL;
while(p1->coef!=0)
{n=n+1;
if(n==1)La=p1;
else p2->next=p1;
p2=p1;
p1=(struct term *)malloc(sizeof(struct term));
scanf("%d,%d",&p1->coef,&p1->expn);
}
p2->next=NULL;
return(La);
}
void print(struct term *La)
{struct term *p;
printf("\nNOW,there %d items are :\n",n);
p=La;
if(La!=NULL)
do
{printf("%d%d",p->coef,p->expn);
p=p->next;}while(p!=NULL);
}
void sort(struct term *La)
{struct term *q,*p,*r;
int i,j,temp,ts,min,max;
p=La;
q=p->next;
while(p!=NULL)
{max=p->coef;
min=p->expn;
r=p;
while(q!=NULL)
{if(min>q->expn)
{max=q->coef;min=q->expn;r=q;}
q=q->next;}
temp=p->expn;ts=p->coef;
p->expn=r->expn;p->coef=r->coef;
r->expn=temp;r->coef=ts;
p=p->next;
q=q->next;
}
}
void *add(struct term *La,struct term *Lb)
{struct term *p1,*p2,*mid;
p1=La->next;p2=Lb->next;mid=Lb->next;
while(p1&&p2)
{if(p1->expn<p2->expn)
{La=p1;p1=p1->next;}
else if(p1->expn==p2->expn)
{p1->coef=p1->coef+p2->coef;mid=mid->next;
if(p1->coef==0)
{La->next=p1->next;free(p1);}
mid=p2;Lb->next=p2->next;free(p2);
p2=p2->next;p1=p1->next;}
else if(p1->expn>p2->expn)
{Lb->next=p2->next;La->next=p2;
p2->next=p1;mid=p2;
p2=p2->next;p1=p1->next;}
}
if(Lb)p1->next=p2;free(p2);
return(La);
}
main()
{struct term *La,*Lb;
printf("\ninput the La:\n" );
La=creat();
print(La);
printf("\ninput the Lb:\n");
Lb=creat();
print(Lb);
sort(La);
print(La);
sort(Lb);
print(Lb);
add(La,Lb);
print(La);
}