1-线性表-1:一元多项式的加法(C语言实现)

题目如下:

设计程序求两个一元多项式的和。

输入格式:

输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数。数字间以空格分隔。

输出格式:

输出1行,以指数递降方式输出和多项式非零项的系数和指数(保证不超过整数的表示范围)。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0。

输入样例

4 3 4 -5 2  6 1  -2 0
3 5 20  -7 4  3 1

输出样例:

5 20 -4 4 -5 2 9 1 -2 0

代码如下:

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int coef;
    int index;
    struct node *next;
};

struct node *Read()
{
    struct node *head, *tail, *p;
    int i, n;
    head = (struct node *)malloc(sizeof(struct node));
    head->next = NULL;
    tail = head;
    scanf("%d", &n);
    for (i = 1; i <= n; i++)
    {
        p = (struct node *)malloc(sizeof(struct node));
        scanf("%d %d", &p->coef, &p->index);
        p->next = NULL;
        tail->next = p;
        tail = p;
    }
    tail->next = NULL;
    return head;
}

struct node *addition(struct node *L1, struct node *L2)
{
    struct node *t1, *t2, *L3, *p, *head;
    t1 = L1->next;
    t2 = L2->next;
    head = (struct node *)malloc(sizeof(struct node));
    head->next = NULL;
    L3 = head;
    while (t1 && t2)
    {
        p = (struct node *)malloc(sizeof(struct node));
        if (t1->index == t2->index)
        {
            p->coef = t1->coef + t2->coef;
            p->index = t1->index;
            t1 = t1->next;
            t2 = t2->next;
        }
        else if (t1->index < t2->index)
        {
            p->coef = t2->coef;
            p->index = t2->index;
            t2 = t2->next;
        }
        else if (t1->index > t2->index)
        {
            p->coef = t1->coef;
            p->index = t1->index;
            t1 = t1->next;
        }
        L3->next = p;
        L3 = L3->next;
    }
    if (t1)
        L3->next = t1;
    else if (t2)
        L3->next = t2;
    return head;
}

void Print(struct node *L)
{
    struct node *p = L->next;
    int flag = 1;
    for (; p; p = p->next)
    {
        if (flag == 0 && p->coef)
        {
            printf(" ");
        }
        if (p->coef)
        {
            printf("%d %d", p->coef, p->index);
            flag = 0;
        }
    }
    if (flag == 1)
        printf("0 0");
    printf("\n");
}

int main()
{
    struct node *L1, *L2, *head;
    L1 = Read();
    L2 = Read();
    head = addition(L1, L2);
    Print(head);
    return 0;
}

运行结果:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值