单链表实现多项式的存储和加法

采用单向链表实现一元多项式的存储并实现两个多项式相加并输出结果。

算法分析:

不采用申请新节点的方法,要充分利用老节点。

代码实现如下:

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

using namespace std;

typedef struct node
{
    int coef,exp;
    struct node *next;

} JD,*LinkList;

LinkList Create()
{
    LinkList head,p,q;
    int c,e;
    head=(LinkList)malloc(sizeof(JD));
    p=head;
    head->next=NULL;
    cin>>c>>e;
    while(c!=0&&e!=0)
    {
        q=(LinkList)malloc(sizeof(JD));
        q->coef=c;
        q->exp=e;
        q->next=NULL;
        p->next=q;
        p=p->next;
        cin>>c>>e;
    }
    return head;
}

void Add(LinkList &LA,LinkList &LB,LinkList &LC)
{
    LinkList pa,pb,pc;
    pa=LA->next;
    pb=LB->next;
    pc=LC;
    while(pa!=NULL&&pb!=NULL)
    {
        if(pa->exp<pb->exp)
        {
            pc->next=pa;
            pc=pa;
            pa=pa->next;
        }
        if(pa->exp>pb->exp)
        {
            pc->next=pb;
            pc=pb;
            pb=pb->next;
        }
        if(pa->exp==pb->exp)
        {
            int m=pa->coef+pb->coef;
            //cout<<"asjkdf"<<pa->coef<<"jswfaio"<<pb->coef<<endl;
            //cout<<"M= "<<m<<endl;
            if(m!=0)
            {
                pa->coef=m;
                pc->next=pa;
                pc=pa;
                pa=pa->next;
                LinkList t=pb;
                pb=pb->next;
                free(t);
            }
            else
            {
                LinkList t=pb;
                pb=pb->next;
                free(t);
                t=pa;
                pa=pa->next;
                free(t);
            }
        }
    }
    if(pa!=NULL)
    {
        pc->next=pa;
    }
    else
    {
        pc->next=pb;
    }
}

void Display(LinkList head)
{
    LinkList p;
    p=head->next;
    while(p!=NULL)
    {
        cout<<p->coef<<" "<<p->exp<<"    ";
        p=p->next;
    }
    cout<<endl;
}

int main()
{
    LinkList head,h1,h2;
    cout<<"Please input the first equation:"<<endl;
    h1=Create();
    cout<<"Please input the second equation:"<<endl;
    h2=Create();
    head=(LinkList)malloc(sizeof(JD));
    head->next=NULL;
    cout<<"The first equation is: "<<endl;
    Display(h1);
    cout<<"The second equation is: "<<endl;
    Display(h2);
    Add(h1,h2,head);
    cout<<"The result equation is: "<<endl;
    Display(head);
    return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值