PAT 1009(甲级) Product of Polynomials

1.简单题直接开辟数组在对应的下标作为指数的情况下,保存每一项的系数即可。注意数组开的足够大,至少是2000;
2.我用的链表,有一处坑点是注意系数可能取负值。

#include<iostream>
#include<iomanip>

using namespace std;
typedef struct node{
    int e;
    float c;
    node *next;
}*Node;//结构体存储每一项的指数e和系数c

int main()
{
    cout.setf(ios::showpoint); //将小数精度后面的0显示出来

    int a;
    node *str1, *str2,*result;
    cin >> a;
    Node p;

    str1 = (Node)malloc(sizeof(Node));
    p = str1;

    while (a--)
    {
        Node q = (Node)malloc(sizeof(node));
        p->next = q;
        p = p->next;
        cin >> p->e>>p->c;
    }
    p->next = NULL;

    cin >> a;
    str2 = (Node)malloc(sizeof(Node));
    p = str2;
    while (a--)
    {
        Node q = (Node)malloc(sizeof(Node));
        p->next = q;
        p = p->next;
        cin >> p->e >> p->c;
    }
    p->next = NULL;//输入分别将两个多项式写入链表str1和str2

    int sum = 0;

    result = (Node)malloc(sizeof(node));
    p = result;
    p->next = NULL;

    p = str1;
    while (p->next)
    {
        p = p->next;
        Node q = str2;
        while (q->next)
        {
            q = q->next;
            int e = p->e + q->e;
            float c = p->c*q->c;
            for (Node r = result; r!= NULL; r = r->next)
            {
                if (r->next==NULL||e > r->next->e)//如果result中没有指数为e的一项,则开辟新的结点
                {
                    Node t = (Node)malloc(sizeof(node));
                    sum++;
                    t->e = e;
                    t->c = c;

                    t->next = r->next;
                    r->next = t;
                    break;
                }
                else if (e == r->next->e)
                {
                    r->next->c += c;
                    if (r->next->c == 0.0)//如果某一项系数为0,则删去该结点
                    {
                        r->next = r->next->next;
                        sum--;
                    }
                    break;
                }
            }
        }
    }

    p = result;
    cout << sum;
    if (sum==0)
        cout << endl;
    while (sum--)
    {
        p = p->next;

        cout << ' ' << p->e<< ' ';
        printf("%.1f", p->c);
        if (p->next==NULL)
        {
            cout << endl;
            break;
        }
    }
    system("pause");
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值