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

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

相关推荐
Boop_wu17 小时前
[数据结构] 栈 · Stack
数据结构
kk”18 小时前
C语言快速排序
数据结构·算法·排序算法
3壹18 小时前
数据结构精讲:栈与队列实战指南
c语言·开发语言·数据结构·c++·算法
papership19 小时前
【入门级-算法-6、排序算法:选择排序】
数据结构·算法·排序算法
YS_Geo21 小时前
Redis 深度解析:数据结构、持久化与集群
数据结构·数据库·redis
njxiejing21 小时前
Pandas数据结构(DataFrame,字典赋值)
数据结构·人工智能·pandas
tju新生代魔迷21 小时前
数据结构:单链表以及链表题
数据结构·链表
dragoooon3421 小时前
[数据结构——lesson3.单链表]
数据结构·c++·leetcode·学习方法
hsjkdhs21 小时前
数据结构之链表(单向链表与双向链表)
数据结构·链表·指针
云泽8081 天前
数据结构之单链表和环形链表的应用(二)-
数据结构