/*-------多项式的加法(考虑在不同情况,三个指针的问题移位,注意在当jubge=0,sum=0的情况下,r指针不用移位)----*/
#include <iostream.h>
#define ok 1;
#define error 0;
typedef int elemtype;
typedef struct lnode{
lnode *next;
elemtype expn;
elemtype coef;
} lnode,*linklist;
static int count=1;
bool createlist(linklist &h,int n){
linklist p,q;
h=new lnode;
h->next=NULL;
q=h;
cout<<"input data:"<<endl;
if(n<0) return error;
for(int i=0;i<n;i++){
p=new lnode;
cin>>p->coef>>p->expn;
p->next=q->next;
q->next=p;
q=q->next;
}
return ok;
}
bool printlist(linklist h){
linklist p;
p=h->next;
while(p!=NULL){
if(p->next!=NULL)
cout<<'('<<p->coef<<'^'<<p->expn<<')'<<'+';
else cout<<'('<<p->coef<<'^'<<p->expn<<')'<<endl;
p=p->next;
}
return ok;
}
/*-----------------多项式加法的实现----------*/
bool addpolyn(linklist &ha,linklist &hb){
linklist p1,r,p2;
p1=ha->next;
r=ha;
p2=hb->next;
elemtype jubge,sum;
while (p1!=NULL&&p2!=NULL){//分三种情况处理
jubge=p1->expn-p2->expn;
if(jubge>0){
cout<<'1';
p1=p1->next;
r=r->next;
}
else if(jubge<0){
cout<<'2';
r->next=p2;
p2=p2->next;
r->next->next=p1;
r=r->next;
}
else{//指数相等时:分系数先加等于0和不等于0两中情况
sum=p1->coef+p2->coef;
if(sum!=0){
cout<<3;
p1->coef=sum;
p1=p1->next;
r=r->next;
p2=p2->next;
}
else {
cout<<4;
p2=p2->next;
r->next=p1->next;
p1=p1->next;
}
}
}
if(p2!=NULL) r->next=p2;
return ok;
}
void main(){
linklist ha,hb;
int na,nb;
cout<<"输入ha数据(项数/系数/指数):"<<endl;
cin>>na;
createlist(ha,na);
printlist(ha);
cout<<"输入hb数据(项数/系数/指数):"<<endl;
cin>>nb;
createlist(hb,nb);
printlist(hb);
// cout<<'s';
cout<<"相加结果:";
addpolyn(ha,hb);
printlist(ha);
}