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

复制代码
#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

相关推荐
kesifan1 天前
数据结构栈和队列
数据结构
TrueFurina(互关互赞)1 天前
7-4 区间水仙花数 Python程序设计-MJU实验四(编程入门•多代码实现•测试均通过)
数据结构·算法·飞书·创业创新·学习方法·远程工作·改行学it
2301_789015621 天前
每日精讲:环形链表、两个数组中的交集、随机链表的复制
c语言·数据结构·c++·算法·leetcode·链表·排序算法
2301_789015621 天前
C++:二叉搜索树
c语言·开发语言·数据结构·c++·算法·排序算法
菜鸟233号1 天前
力扣669 修剪二叉搜索树 java实现
java·数据结构·算法·leetcode
jingfeng5142 天前
哈希表的概念+实现
数据结构·哈希算法·散列表
ホロHoro2 天前
数据结构非线性部分(1)
java·数据结构·算法
沉下去,苦磨练!2 天前
实现二维数组反转
java·数据结构·算法
玖剹2 天前
哈希表相关题目
数据结构·c++·算法·leetcode·哈希算法·散列表
红豆诗人2 天前
数据结构初阶知识--单链表
c语言·数据结构