多项式加法
in Solutions with 0 comment

多项式加法

in Solutions with 0 comment

简单多项式加法代码

#include <bits/stdc++.h>

struct dudeNode{
    int32_t Coefficient;
    int32_t Exponent;
    dudeNode* next;
    dudeNode(int32_t c=0,int32_t e=0):Coefficient(c),Exponent(e){}
};


dudeNode* build(std::vector<int32_t> coeffs,std::vector<int32_t> exp){
    dudeNode* dummy=new dudeNode();
    dudeNode* cur=dummy;
    for(int i=0;i<coeffs.size();++i){
        cur->next=new dudeNode(coeffs[i],exp[i]);
        cur=cur->next;    
    }
    return dummy;
}

void display(dudeNode* dude){
    while(dude->next!=nullptr){
        std::cout<<dude->next->Coefficient<<"x"<<dude->next->Exponent<<"  ";
        dude=dude->next;
    }
    std::cout<<std::endl;
}


dudeNode* Add(dudeNode* a,dudeNode* b){
    dudeNode* result=(dudeNode*)malloc(sizeof(dudeNode));
    dudeNode* curResult=result;
    dudeNode* curA=a;
    dudeNode* curB=b;
    curA=curA->next;
    curB=curB->next;
    while(curA!=nullptr&&curB!=nullptr){
        if(curA->Exponent>curB->Exponent){
            curResult->next=curA;
            curResult=curResult->next;
            curA=curA->next;
        }else if(curA->Exponent<curB->Exponent){
            curResult->next=curB;
            curResult=curResult->next;
            curB=curB->next;
        }else{
            dudeNode* newNode=(dudeNode*)malloc(sizeof(dudeNode));
            newNode->Coefficient=curA->Coefficient+curB->Coefficient;
            if(newNode->Coefficient==0){
                curA=curA->next;
                curB=curB->next;
                continue;
            }
            newNode->Exponent=curA->Exponent;
            curA=curA->next;
            curB=curB->next;
            curResult->next=newNode;
            curResult=curResult->next;
        }
    }
    if(curA!=nullptr){
        curResult->next=curA;
    }
    if(curB!=nullptr){
        curResult->next=curB;
    }
    return result;
}

int main()
{
    dudeNode* a=build({4,3,2,1},{8,7,6,5});
    dudeNode* b=build({},{});
    dudeNode* result=Add(a,b);
    display(result);

}
Responses