链表实现多项式运算

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

typedef struct ListNode
{
    int ratio;
    int expton;
    struct ListNode *next;
}List;

List *CreatList ()
{
    List *e1, *e2, *L;
    L = NULL;
    int expton;
    printf("Enter expton:");
    scanf("%d", &expton);
    while(expton != -1)        //-1表示输入的结束
    {
        e1 = (List *)malloc(sizeof(struct ListNode));
        e1->expton = expton;
        e1->next = NULL;
        printf("Enter ratio:");
        scanf("%d", &(e1->ratio));
        if(!L)
        {
            L = e1;
        }
        else
        {
            e2->next = e1;
        }
        e2 = e1;
        printf("Enter expton:");
        scanf("%d", &expton);
    }
    return L;
}

void PrintList (List *L)
{
    List *e;
    e = L;
    for(e; e != NULL; e = e->next)
    {
        printf("%d %d\n", e->ratio, e->expton);
    }
}

List *AddList (List *L1, List *L2)
{
    List *L3, *e1, *e2;
    L3 = NULL;
    while(L1 && L2)
    {
        e1 = (List *)malloc(sizeof(struct ListNode));
        e1->next = NULL;
        if(L1->expton == L2->expton)
        {
            e1->expton = L1->expton;
            e1->ratio = L1->ratio + L2->ratio;
            L1 = L1->next;
            L2 = L2->next;
        }
        else if(L1->expton > L2->expton)
        {
            e1->expton = L1->expton;
            e1->ratio = L1->ratio;
            L1 = L1->next;
        }
        else
        {
            e1->expton = L2->expton;
            e1->ratio = L2->ratio;
            L2 = L2->next;
        }
        if(!L3)
        {
            L3 = e1;
        }
        else
        {
            e2->next = e1;
        }
        e2 = e1;
    }
    while(L1)
    {
        e1 = (List *)malloc(sizeof(struct ListNode));
        e1->next = NULL;
        e1->expton = L1->expton;
        e1->ratio = L1->ratio;
        L1 = L1->next;
        e2->next = e1;
        e2 = e1;
    }
    while(L2)
    {
        e1 = (List *)malloc(sizeof(struct ListNode));
        e1->next = NULL;
        e1->expton = L2->expton;
        e1->ratio = L2->ratio;
        L2 = L2->next;
        e2->next = e1;
        e2 = e1;
    }
    return L3;
}

int main ()
{
    List *L1, *L2, *L3;
    L1 = CreatList();
    L2 = CreatList();
    L3 = AddList(L1, L2);
    PrintList(L3);
    return 0;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值