数据结构(线性表的链式实现):稀疏多项式

复制代码
#include <iostream>
//稀疏多项式合并
typedef struct PNode
{
    int expn;//指数
    float  coef;//系数
    struct PNode *next;
}PNode,*Polyn;
void create_polyn(Polyn &s,int n)
{
    s=new PNode ;//头节点
    s->next=nullptr;
    PNode *q=new PNode;
    PNode *pre=new PNode;
    q=s;
    for (int i = 0; i < n; ++i) {
        PNode *e=new PNode; //局部变量保存新节点
        std::cin>>e->coef>>e->expn;
        pre=s;//q的前驱
        q=s->next;//每次选位置前,q都要指向首元结点
        while (q&&q->expn<e->expn)
        {
            pre=q;
            q=q->next;
        }
        //插入e
        e->next=q;
        pre->next=e;
    }
}
void Add_Polyn(Polyn &a,Polyn &b)
{
//相同指数,对应系数加,不同指数,小的先放,合并到a
    PNode *ap=new PNode ;
    PNode *bp=new PNode ;
    PNode *apre=new PNode ;
    PNode *bpre=new PNode ;
    ap=a->next,bp=b->next;
    apre=a,bpre=b;
    float  sum;
    while (ap&&bp)
    {
        PNode *node;
        if(ap->expn==bp->expn)
        {//指数相等,系数相加不等于0和等于0
            sum = ap->coef + bp->coef;
            if (sum!=0) {
                ap->coef = sum;
                node=bp;
                bpre->next=bp->next;
                bp = bp->next;
                ap = ap->next;
                apre = apre->next;
                delete node;
            } else {
                node=ap;
                apre->next = ap->next;
                ap = ap->next;
                delete node;
                bpre->next = bp->next;
                node=bp;
                bp = bp->next;
                delete node;
            }
        }
        else if(ap->expn>bp->expn)
        {
            bp->next=ap;
            apre->next=bp;
            apre=bp;
            bpre=bp;
            bp=bp->next;
        } else{
            apre=ap;
            ap=ap->next;
        }

    }
//剩下的
    while (bp){
        ap->next=bp;
        bp=bp->next;
    }
}
void output(Polyn a)
{
    a=a->next;
    while (a)
    {
        printf("%0.2f %d  ",a->coef,a->expn);
        a=a->next;
    }
    printf("\n");

}
int main() {
    //两个稀疏多项式a,b
    Polyn a,b;
    int a_len,b_len;
    std::cin>>a_len;
    std::cin>>b_len;
    create_polyn(a,a_len);
    create_polyn(b,b_len);
    output(a);
    output(b);
    Add_Polyn(a,b);
    output(a);
    return 0;
}

input

c*x^y 输入系数c,指数y

4 3

3 0 2 2 -5 1 7 3

5 0 10 1 -2 2

相关推荐
Chester_19992 小时前
CSP202312C.树上搜索
开发语言·数据结构·c++·蓝桥杯·stl
专注仿真4 小时前
RabbitMQ消息队列实战项目
数据结构·rabbitmq
血小板要健康4 小时前
队列 + 宽搜(BFS):二叉树层序遍历 算法总结
java·数据结构·笔记·算法·leetcode·宽度优先
Felven5 小时前
B. Deja Vu
数据结构·算法
不会就选b6 小时前
算法日常・每日刷题--<贪心>3
数据结构·算法·leetcode
ysu_03146 小时前
03-双链表与循环链表
c语言·数据结构·链表
wabs6667 小时前
关于二叉树【力扣107.二叉树的层序遍历II的思考】
数据结构·c++·算法·leetcode·二叉树·层序遍历
小七在进步8 小时前
数据结构:非比较排序:计数排序
数据结构
一木 之林8 小时前
四、STL 容器与数据结构(进阶)(二)
数据结构·c++·哈希算法
ysu_03148 小时前
02-单链表完全指南
c语言·数据结构·算法·leetcode