使用链表求一元多项式的和

#include <iostream>
#include <stdlib.h>
using namespace std;
struct node
{
    int coefficient;
    int exponent;
    struct node *next;
};
struct node *creat()//建立单链表返回链表头指针,此头指针无数据
{
    struct node *head,*p1,*p2;
    int c,e;
    head=(struct node*)malloc(sizeof(struct node));//先为头指针开一个内存
    head->next=NULL;
    p2=head;//为了使头指针不变,所以定义指针p2代替头指针
    cin>>c>>e;
    while(e!=-1)
    {
        p1=(struct node*)malloc(sizeof(struct node));
        p1->coefficient=c;
        p1->exponent=e;
       p1->next=NULL;
        p2->next=p1;
        p2=p1;
        cin>>c>>e;
    }
    return head;//最终该头指针无内容
}
void print(struct node *head)//输出链表
{
    struct node *p;
    p=head;
    p=p->next;//因为头指针head为空,head->next为第一个元素,所以p=p->next;
    while(p!=NULL)
    {
        cout<<p->coefficient<<'x'<<p->exponent<<' ';
        p=p->next;
    }
    cout<<endl;
}
//默认输入为重小到大
struct node *add(struct node *t1,struct node*t2)//相加
{
    struct node *p,*q,*prea,*preb;//建立prea和preb指针的作用在于当p和q指针要指向下一个数字的时候,先复制它们的位置
    int sum;                      //等到判断的时候方便进行指针指向的改变
    p=t1->next;//t1空,p指向第一个元素
    q=t2->next;//同理
    prea=t1;//把prea作为头指针
    //注意while里面必须用else if而不是if因为是3个选一个进行而不是并列的进行满足一个条件会影响下一个if的判断
    while(p!=NULL&&q!=NULL)
    {
        if(p->exponent<q->exponent)
        {
            prea=p;
            p=p->next;
        }
       else if(p->exponent==q->exponent)
        {
            sum=p->coefficient+q->coefficient;
            if(sum!=0)
            {
                p->coefficient=sum;
                prea=p;
                preb=q;
                p=p->next;
                q=q->next;
            }
            if(sum==0)//正负相加为0
            {
                p=p->next;
               preb=q;
                prea->next=p;
                q=q->next;
            }
        }
        else
        if(p->exponent>q->exponent)//插入
        {
            preb=q;
            q=q->next;
            preb->next=p;
            prea->next=preb;
            prea=prea->next;
        }//这个里面没有浦p=p->next是因为当插入完之后preb与p进行判断看是否可以进行合并同类项
    }
    if(q!=NULL)
        prea->next=q;
    return t1;
}
int main()
{
    struct node *heada,*headb,*headc;
    heada=creat();
    print(heada);
    headb=creat();
    print(headb);
    headc=add(heada,headb);
    print(headc);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值