实验完整代码
#include<stdio.h>
#include<malloc.h>
typedef struct node{
float coef;//系数
int index;//指数
struct node *next;
} Polylist;
//头插法建单链表
Polylist *CreateT(){
Polylist *head,*s;
float x;
int y;
int i=1;
head=(Polylist *)malloc(sizeof(Polylist));
head->coef=1;
head->index=99999;
head->next=NULL;
printf("请输入第%d项系数与指数:\n",i);
scanf("%f %d",&x,&y);
while(x!=0){
s=(Polylist *)malloc(sizeof(Polylist));
s->coef=x;
s->index=y;
s->next=head->next;
head->next=s;
i++;
printf("请输入第%d项系数与指数:\n",i);
scanf("%f %d",&x,&y);
}
return head;
}
//尾插法建单链表(仅仅练习下写法,不适用)
Polylist *CreateW(){
Polylist *head,*r,*s;
float x;
int y;
int i=1;
head=(Polylist *)malloc(sizeof(Polylist));
head->coef=1;
head->index=99999;
head->next=NULL;
r=head;
printf("请输入第%d项系数与指数:\n",i);
scanf("%f %d",&x,&y);
while(x!=0){
s=(Polylist *)malloc(sizeof(Polylist));
s->coef=x;
s->index=y;
r->next=s;
r=s;
i++;
printf("请输入第%d项系数与指数:\n",i);
scanf("%f %d",&x,&y);
}
r->next=NULL;
return head;
}
//两个多项式相加
void AddPoly(Polylist *heada,Polylist *headb){
Polylist *pa,*pb;
Polylist *pre,*r;//pre标记当前pa结点前去结点,r标记当前pb结点后继结点
float x;
pa=heada->next;
pb=headb->next;
pre=heada;
while(pa!=NULL && pb!=NULL){
if(pa->index<pb->index){ //pa结点指数小于pb结点指数
pre=pa;
pa=pre->next;//后移pa结点
}
else if(pa->index==pb->index){ //pa结点指数等于pb结点指数
x=pa->coef+pb->coef;
if(x==0) { //系数相加等于0
pre->next=pa->next;
free(pa);
}
else{ //系数相加不等0
pa->coef=x;
pre=pa;
}
pa=pre->next;//pa指针后移
r=pb;
pb=r->next;//pb指针后移
free(r);
}
else if(pa->index>pb->index){ //pa结点指数大于pb结点指数
r=pb->next;
pre->next=pb;
pb->next=pa;//pb结点插入pa结点前
pre=pb;
pb=r;
}
}
if(pb!=NULL){ //pb中有剩余结点连接在pa后
pre->next=pb;//思考为什么不是pa->next=pb?(此时pa==NULL)
}
free(pb); //删除剩下的pb结点
}
//遍历多项式
void Show(Polylist *head){
Polylist *p;
p=head->next;
while(p->next!=NULL){
printf("%.1fX%d+",p->coef,p->index);
p=p->next;
}
printf("%.1fX%d\n",p->coef,p->index);
}
//测试
int main(){
Polylist *la,*lb;
printf("请输入第一个一元多项式(ListA)的系数与指数,以0结束所有输入:\n");
la=CreateW();
printf("ListA:\n");
Show(la);
printf("\n请输入第二个一元多项式(ListB)的系数与指数,以0结束所有输入:\n");
lb=CreateW();
printf("ListB:\n");
Show(lb);
printf("\nListA与ListB两个一元多项式的和为:\n");
AddPoly(la,lb);
printf("ListA+ListB:\n");
Show(la);
}
实验结果