いちじたこうしきかさん


次のプログラムは、1元多項式の加算演算を実現します.
//       
//   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;
}