C++多项式的加法

#include<iostream>
using namespace std;
typedef struct LNode {
    int coef;
    int exp;
    LNode* next;
}LNode;
class poly {
    LNode* head;
public:
    void create(int n);//创建n项的多项式
    int comp(int a, int b);
    void addpoly(poly& ha, poly hb);
    void print();
};
void poly::create(int n) {
    head = new LNode;
    head->next = NULL;
    LNode* p;
    for (int i = 0; i < n; i++) {
        p = new LNode;
        cin >> p->coef >> p->exp;//升序输入
        p->next = head->next;
        head->next = p;
    }
}
int poly::comp(int a, int b) {
    if (a > b)return -1;
    else if (a == b)return 0;
    else return 1;
}
void poly::addpoly(poly& ha, poly hb) {
    LNode* q = ha.head, * pa = ha.head->next, * pb = hb.head->next, * r;
    while (pa && pb)
        switch (comp(pa->exp, pb->exp)) {
        case -1: q = pa; pa = pa->next;
            break;
        case 0: pa->coef += pb->coef;
            if (pa->coef == 0) {
                q->next = pa->next;
                delete pa;
                pa = q;
            }
            else q = pa;
            pa = pa->next;
            pb = pb->next;
            break;
        case 1:  r = new  LNode;
            r->coef = pb->coef;
            r->exp = pb->exp;
            q->next = r;
            r->next = pa;
            q = r;
            pb = pb->next;
            break;
        }
    while (pb != NULL) {
        r = new LNode;
        r->coef = pb->coef;
        r->exp = pb->exp;
        q->next = r;
        r->next = pa;
        q = r;
        pb = pb->next;
    }
}
void poly::print() {
    LNode* p = head->next;
    while (p) {
        cout << p->coef << ' ' << p->exp << ' ';
        p = p->next;
    }
    cout << endl;
}
int main() {
    poly ha, hb;
    cout << "创建多项式 1:" << endl;
    ha.create(1); //创建 ha
        cout << "创建多项式 2:" << endl;
    hb.create(2); // 创建 hb
        ha.print();
    hb.print();
    ha.addpoly(ha, hb); // 多项式相加
        cout << "多项式之和:" << endl;
    ha.print(); // 输出运算后的多项式
        return 0;
}

欢迎指正

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爆炒江湖!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值