下面的程序实现了一元多项式的加法运算:
//一元多项式加法 //单链表La,Lb,结果存在Lc中 #include<iostream> using namespace std; typedef struct Term{ double coef; //系数 int expn; //指数 struct Term *next; }; int main(){ //La Term *headA=new Term; headA->coef=NULL; headA->expn=NULL; headA->next=NULL; int c,e; Term *p; p=headA; while(cin>>c>>e){ if(c==0&&e==0) break; Term *q=new Term; q->coef=c; q->expn=e; q->next=NULL; p->next=q; p=q; } cin.ignore(); //Lb Term *headB=new Term; headB->coef=NULL; headB->expn=NULL; headB->next=NULL; p=headB; while(cin>>c>>e){ if(c==0&&e==0) break; Term *q=new Term; q->coef=c; q->expn=e; q->next=NULL; p->next=q; p=q; } //Lc Term *headC=new Term; headC->coef=NULL; headC->expn=NULL; headC->next=NULL; Term *q,*r; p=headA->next; q=headB->next; r=headC; while(p!=NULL&&q!=NULL){ if(p->expn==q->expn){ p->coef=(p->coef)+(q->coef); r->next=p; r=p; p=p->next; q=q->next; } else{ if(p->expn>q->expn){ r->next=q; r=q; q=q->next; } else{ r->next=p; r=p; p=p->next; } } } if(p!=NULL) r->next=p; if(q!=NULL) r->next=q; r=headC->next; while(r!=NULL){ if(r->coef!=0) cout<<r->coef<<" "<<r->expn<<endl; r=r->next; } delete p; delete q; delete r; return 0; }