【线性表】单链表的运用 多项式的代数运算

目录

1.多项式的创建和打印

2.多项式的相加相乘

3.多项式示例


1.多项式的创建和打印

#include <iostream>
using namespace std;
typedef struct PolyNode {
    int coef; //系数
    int expn; //指数
    PolyNode *next;
} *LIST, *Node;

void CreatPolyList(LIST &L, int n)
{
    Node node, last; //与单链表的创建同理
    L = last = new PolyNode;
    cout << "输入成对的系数和指数: " << endl;

    for (int i = 0; i < n; i++) {
        node = new PolyNode;
        last->next = node;
        cin >> node->coef >> node->expn;
        last = node;
    }
    last->next = NULL;
}

void PrintPolyList(LIST &L)
{
    Node p = L->next; //与单链表的输出同理
    cout << p->coef << "X^" << p->expn;

    for (p = p->next; p; p = p->next) {
        cout << "+" << p->coef << "X^" << p->expn;
    }
    cout << endl;
}

2.多项式的相加相乘

LIST Plus(LIST &L1, LIST &L2)
{   //多项式相加类似于单链表的归并
    Node node, last, p1 = L1->next, p2 = L2->next;
    LIST L = last = new PolyNode;

    while (p1 && p2) {
        if (p1->expn > p2->expn) {
            last->next = p1;
            last = p1;
            p1 = p1->next;
        } else if (p1->expn < p2->expn) {
            last->next = p2;
            last = p2;
            p2 = p2->next;
        } else {
            Node node = new PolyNode;
            node->coef = p1->coef + p2->coef;
            node->expn = p1->expn;
            last->next = node;
            last = node;
            p1 = p1->next; //由于此条件下相加了两个同指数项!
            p2 = p2->next; //所以两个表的待插入结点都需要更新
        }
    }
    last->next = p1 ? p1 : p2; //复制表中剩余结点

    return L;
}

LIST Multiply(LIST &L1, LIST &L2)
{
    Node p, p1, p2, last;
    LIST L = last = new PolyNode;
    p1 = L1->next;
    while (p1 != NULL) {
        p2 = L2->next;
        while (p2 != NULL) {
            p = new PolyNode;
            p->coef = (p1->coef) * (p2->coef);
            p->expn = (p1->expn) + (p2->expn);
            last->next = p;
            last = p;
            p2 = p2->next;
        }
        p1 = p1->next;
    }
    last->next = NULL;
    return L;
}

3.多项式示例

int main()
{
    LIST L1, L2, L3, L4;
    CreatPolyList(L1, 2);
    cout << "创建的多项式1";
    PrintPolyList(L1);

    CreatPolyList(L2, 2);
    cout << "创建的多项式2";
    PrintPolyList(L2);

    cout << "多项式相加后为: ";
    L3 = Plus(L1, L2);
    PrintPolyList(L3);

    cout << "多项式相乘后为: ";
    L4 = Multiply(L1, L2);
    PrintPolyList(L4);
    
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值