求C语言一元多项式相加,用链表完成
#include<stdio.h>#include<malloc.h>
/*多项式数据类型的定义*/
typedef struct poly
{
float coef;
int exp;
struct poly *next;
}polytype;
/*创建链表*/
polytype * create()
{
polytype *h,*r,*s;
float c;
int e;
h=(polytype *)malloc(sizeof(polytype)); //申请表头结点空间
r=h;
printf("coef:");
scanf("%f",&c);
printf("exp: ");
scanf("%d",&e);
while(c!=0)
{
s=(polytype *)malloc(sizeof(polytype));
s->coef=c;
s->exp=e;
r->next=s;
r=s;
printf("coef:");
scanf("%f",&c);
printf("exp: ");
scanf("%d",&e);
}
r->next=NULL;
return(h);
}
/*多项式相加函数*/
void polyadd(polytype *pa, polytype *pb)
{
polytype *p,*q,*pre,*temp;
float sum;
p=pa->next;
q=pb->next;
pre=pa;
while(p!=NULL&&q!=NULL)
{
if(p->exp<q->exp)
{
//pre->next=p;
//pre=pre->next;
//p=p->next;
pre=p;
p=p->next;
}
else if(p->exp==q->exp)
{
sum=p->coef+q->coef;
if(sum!=0)
{
/*p->coef=sum;
pre->next=p;
pre=pre->next;
p=p->next;
temp=q;
q=q->next;
free(temp);*/
p->coef=sum;
pre=p;
}
else
{
/*temp=p->next;
free(p);
p=temp;
temp=q->next;
free(q);
q=temp;*/
pre->next=p->next;
free(p);
}
p=pre->next;
temp=q;
q=q->next;
}
else
{
/*pre->next=q;
pre=pre->next;
q=q->next;*/
temp=q->next;
q->next=p;
pre->next=q;
pre=q;
q=temp;
}
}
if(/*p*/q!=NULL)
pre->next=q;//p;
/*else
pre->next=q; */
free(pb);
}
/*输出函数*/
void print(polytype * p)
{
while(p->next!=NULL)
{
p=p->next;
printf(" %g*x^%d",p->coef,p->exp);
}
}
/*主函数*/
main()
{
polytype * pa,* pb;
printf("Welcome to use!\n");
printf("\nPlease input the pa include coef && exp:\n");
pa=create();
print(pa);
printf("\nPlease input the pb include coef && exp:\n");
pb=create();
print(pb);
printf("\nSum of the poly is:\n");
polyadd(pa,pb);
print(pa);
printf("\n");
}
请求修改