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

#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

相关推荐
CS创新实验室3 分钟前
计算机考研之数据结构:P 问题和 NP 问题
数据结构·考研·算法
小王努力学编程3 小时前
【算法与数据结构】单调队列
数据结构·c++·学习·算法·leetcode
万兴丶3 小时前
Unity 适用于单机游戏的红点系统(前缀树 | 数据结构 | 设计模式 | 算法 | 含源码)
数据结构·unity·设计模式·c#
程序员东min3 小时前
数据结构:实验题目:单链表归并。将两个非递减次序排列的单链表归并为一个非递增次序排列的单链表,并计算表长。要求利用原来两个单链表的结点存放合并后的单链表。
数据结构
黄雪超5 小时前
深入HBase——核心组件
数据结构·数据库·hbase
夏末秋也凉5 小时前
力扣-贪心-53 最大子数组和
数据结构·算法·leetcode
OrangeJiuce8 小时前
【QT中的一些高级数据结构,持续更新中...】
数据结构·c++·qt
萌の鱼11 小时前
leetcode 2826. 将三个组排序
数据结构·c++·算法·leetcode
Buling_011 小时前
算法-哈希表篇08-四数之和
数据结构·算法·散列表
左灯右行的爱情13 小时前
Redis数据结构总结-listPack
数据结构·数据库·redis