多项式的加法(链表)

这篇博客探讨了如何使用链表数据结构来实现两个多项式的加法操作。首先介绍了链表的基本概念,然后详细阐述了如何将多项式的系数和指数映射到链表节点,并通过遍历链表实现加法。文章最后提供了具体的代码示例,帮助读者理解这一过程。
摘要由CSDN通过智能技术生成
#include<bits/stdc++.h>
using namespace std;

struct node
{
    int zhishu;
    int xishu;
    struct node *next;
};

void Attach(int c,int e,node *pRear)
{
    node *p;
    p=(node *)malloc(sizeof(node));
    p->zhishu=e;
    p->xishu=c;
    p->next=NULL;
    pRear->next=p;
}

node* Read()
{
    int N;
    cin>>N;
    node *P,*Rear;
    P=(node *)malloc(sizeof(node));
    P->next=NULL;
    Rear=P;
    for(int i=0;i<N;i++)
    {
        int a,b;
        cin>>a>>b;
        if(a==0&&b==0)
            break;
            Attach(a,b,Rear);
    }
    node *T;
    T=P;
    P=P->next;
    free(T);
    return P;
}
int compare(int a,int b)
{
    if(a>b)
        return 1;
    else if(a==b)
        return 0;
    else
        return -1;
}
node* Add(node *a,node *b)
{
    node *t1,*t2,*p,*q,*Rear;
    p=(node *)malloc(sizeof(node));
    p->next=NULL;
    Rear=p;
    t1=a;
    t2=b;
    int sum=0;
    while(t1&&t2)
    {
        switch(compare(t1->zhishu,t2->zhishu))
        {
            case 1:
                Attach(t1->xishu,t2->zhishu,p);
                t1=t1->next;
                break;
            case 0:
                sum=t1->xishu+t2->xishu;
                if(sum)
                    Attach(sum,t1->zhishu,p);
                    t1=t1->next;
                    t2=t2->next;
                    break;
            case -1:
                Attach(t2->xishu,t2->zhishu,p);
                t2=t2->next;
                break;
        }
    }
    for(;t1;t1=t1->next)
        Attach(t1->xishu,t1->zhishu,Rear);
    for(;t2;t2=t2->next)
        Attach(t2->xishu,t2->zhishu,Rear);
    Rear->next=NULL;
    node *front1;
    front1 =Rear;
    Rear=Rear->next;
    free(front1);
    return front1;
}
int main()
{

    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值