数据结构实验----链表

一.实验目的

1.理解单链表的结构特性和基本操作算法

2.掌握利用单链表实现两个多项式相加算法

二.实验内容

1.创建两个一元多项式;

2.输出一元多项式;

3.实现两个一元多项式相加;

4.输出相加后的一元多项式。

三.代码

#include <iostream>

using namespace std;

struct PolyNode {
    double coef;
    int exp;
    PolyNode* next;
    PolyNode(double c, int e): coef(c), exp(e), next(NULL) {}
};

PolyNode* create_poly() {
    PolyNode* head = new PolyNode(0, 0);
    PolyNode* cur = head;
    int n;
    cout << "请输入多项式的项数:";
    cin >> n;
    cout << "请按照指数从大到小的顺序依次输入" << n << "项的系数和指数(使用空格分隔):" << endl;
    for (int i = 0; i < n; i++) {
        double coef;
        int exp;
        cin >> coef >> exp;
        cur->next = new PolyNode(coef, exp);
        cur = cur->next;
    }
    return head->next;
}

void print_poly(PolyNode* p) {
    bool first = true;
    while (p) {
        if (p->coef != 0) {
            if (!first && p->coef > 0) {
                cout << "+";
            }
            cout << p->coef;
            if (p->exp > 1) {
                cout << "x^" << p->exp;
            } else if (p->exp == 1) {
                cout << "x";
            }
            first = false;
        }
        p = p->next;
    }
}

PolyNode* add_poly(PolyNode* poly1, PolyNode* poly2) {
    PolyNode* head = new PolyNode(0, 0);
    PolyNode* cur = head;
    PolyNode* p = poly1;
    PolyNode* q = poly2;
    while (p && q) {
        if (p->exp == q->exp) {
            double coef_sum = p->coef + q->coef;
            if (coef_sum != 0) {
                cur->next = new PolyNode(coef_sum, p->exp);
                cur = cur->next;
            }
            p = p->next;
            q = q->next;
        } else if (p->exp > q->exp) {
            cur->next = new PolyNode(p->coef, p->exp);
            cur = cur->next;
            p = p->next;
        } else {
            cur->next = new PolyNode(q->coef, q->exp);
            cur = cur->next;
            q = q->next;
        }
    }
    cur->next = p ? p : q;
    return head->next;
}

int main() {
    PolyNode* poly1 = create_poly();
    cout << "多项式1:";
    print_poly(poly1);
    cout << endl;

    PolyNode* poly2 = create_poly();
    cout << "多项式2:";
    print_poly(poly2);
    cout << endl;

    PolyNode* res = add_poly(poly1, poly2);
    cout << "多项式1 + 多项式2:";
    print_poly(res);
    cout << endl;

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值