美文网首页
多项式求和-Polynomial.cpp

多项式求和-Polynomial.cpp

作者: Jaling | 来源:发表于2022-01-11 10:40 被阅读0次

    “线性表的应用-多项式求和”原文

    ----------------------------------------------------------------------

    #include<iostream>

    #include"Polynomial.h"

    using namespace std;

    //无参构造函数

    Polynomial::Polynomial(){

    this->head = NULL;

    }

    //多项式求和函数

    void Polynomial::Add(Polynomial&A,Polynomial&B){

    //构建sum的头节点

    if(A.head->exp<B.head->exp){

    this->head = A.head;

    }else if(A.head->exp>B.head->exp)

    {

    this->head = B.head;

    }else

    {

    PolyNode *_pn = new PolyNode();

    _pn->coef = A.head->coef + B.head->coef;

    _pn->exp = A.head->exp;

    _pn->next = NULL;

    this->head = _pn;

    }

    PolyNode *rear = this->head;  //当前多项式链表的尾结点

    PolyNode*pa = A.head->next;

    PolyNode*pb = B.head->next;

    while(pa!=NULL&&pb!=NULL){

    //如果pa的指数小于pb的指数,取pa的指数加入头系数后面

    if(pa->exp<pb->exp){

    rear->next = pa;

    rear = pa;

    pa = pa->next;

    }else if(pa->exp=pb->exp)

    {

    float sum = pa->coef + pb->coef;

    if(sum!=0){

    PolyNode *newPN = new PolyNode;

    newPN->coef = sum;

    newPN->exp = pa->exp;

    newPN->next = NULL;

    rear->next = newPN;

    rear = newPN;

    }

    pa = pa->next;

    pb = pb->next;

    }else{

    rear->next = pb;

    rear = pb;

    pb = pb->next;

    }

    }

    if(pa!=NULL){

    rear->next = pa;

    }

    if(pb!=NULL){

    rear->next = pb;

    }

    }

    //多项式控制台输出函数

    void Polynomial::display(){

    PolyNode * p = this->head;

    cout<<"f=";

    while(p){

    if(p->coef==0){

    p = p->next;

    continue;

    }

    cout<<p->coef<<"x"<<p->exp;

    p = p->next;

    if(p)

    cout<<"+";

    }

    cout<<endl;

    }

    相关文章

      网友评论

          本文标题:多项式求和-Polynomial.cpp

          本文链接:https://www.haomeiwen.com/subject/bbjbcrtx.html