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

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

相关推荐
如意猴1 小时前
数据结构初阶(第六讲)单链表的功能实现
数据结构
2401_841495642 小时前
【数据结构】链栈的基本操作
java·数据结构·c++·python·算法·链表·链栈
Archie_IT2 小时前
「深入浅出」嵌入式八股文—P2 内存篇
c语言·开发语言·数据结构·数据库·c++·算法
是那盏灯塔2 小时前
【算法】——动态规划算法及实践应用
数据结构·c++·算法·动态规划
MATLAB代码顾问2 小时前
MATLAB计算标准径流指数(Standard Runoff Index,SRI)
数据结构·算法·matlab
想ai抽4 小时前
吃透大数据算法-霍夫曼编码(Huffman Coding)
大数据·数据结构·算法
Miraitowa_cheems6 小时前
LeetCode算法日记 - Day 63: 图像渲染、岛屿数量
java·数据结构·算法·leetcode·决策树·贪心算法·深度优先
拾光Ծ7 小时前
【数据结构】二叉搜索树 C++ 简单实现:增删查改全攻略
数据结构·c++·算法
小贾要学习7 小时前
编程中常见的排序算法
数据结构·c++·算法·排序算法
Yupureki7 小时前
从零开始的C++学习生活 4:类和对象(下)
c语言·数据结构·c++·学习