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

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

算法分析:

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

代码实现如下:

#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;
}


你可能感兴趣的:(单链表实现多项式相加)