您的位置:首页 > 理论基础 > 数据结构算法

多项式相加

2015-11-03 01:27 447 查看
#include<iostream>

using namespace std;

struct linknode

{
int xishu;
int zhishu;
linknode*next;

};

linknode*create(int n,linknode*head)

{
linknode*newnode,*current;
head=new linknode;
head=NULL;
int xishu,zhishu;
for(int i=0;i<n;i++)
{

        cin>>xishu>>zhishu;
newnode=new linknode;
newnode->xishu=xishu;
newnode->zhishu=zhishu;
newnode->next=NULL;
if(head==NULL)
{
head=newnode;
current=newnode;
}
else
{
current->next=newnode;
current=newnode;
}
}
current->next=NULL;
return head;

}

void display(linknode* head)

{
linknode*p;
p=head;
if(!p)
cout<<"NULL"<<endl;
else{
while(p)
{
if(p->zhishu>0 && p->xishu>0)
cout<<p->xishu<<"x^"<<p->zhishu;
else if(p->xishu<0 && p->zhishu>0)
cout<<"("<<p->xishu<<")"<<"x^"<<p->zhishu;
else if(p->xishu>0 && p->zhishu<0)
cout<<p->xishu<<"x^"<<"("<<p->zhishu<<")";
else if(p->xishu<0&&p->zhishu<0)
cout<<"("<<p->xishu<<")"<<"x^"<<"("<<p->zhishu<<")";
else if(p->zhishu==0 && p->xishu>0)
       
cout<<p->xishu;
else if(p->zhishu==0 && p->xishu<0)
       
cout<<"("<<p->xishu<<")";
else if(p->xishu==0)
cout<<"";
p=p->next;
if(p!=NULL)
cout<<" "<<"+"<<" ";
}
cout<<endl;
}

}

linknode*addlink(linknode *LA,linknode *LB,linknode*LC)

{

    linknode*p1,*p2,*lc,*s;
LC=new linknode;
LC->next=NULL;
lc=LC;
p1=LA;
p2=LB;

// cout<<p1->xishu<<"p1 "<<p1->zhishu<<endl;
// cout<<p1->next->xishu<<"p1 "<<p1->next->zhishu<<endl;

// cout<<p2->xishu<<"p2 "<<p2->zhishu<<endl;
// cout<<p2->next->xishu<<"p2 "<<p2->next->zhishu<<endl;
while(p1!=NULL && p2!=NULL)
{
if(p1->zhishu < p2->zhishu)
{// cout<<"come to p1<p2";
   s=p1->next;
lc->next=p1;
lc=p1;
lc->next=NULL;
p1=s;
}
else if(p1->zhishu == p2->zhishu)
{
p1->xishu=p1->xishu+p2->xishu;
if(p1->xishu!=0)
{
// cout<<"come to !=0";
s=p1->next;
lc->next=p1;
lc=p1;
lc->next=NULL;
p1=s;
p2=p2->next;
// cout<<p1->zhishu<<" p1 "<<p1->xishu<<endl;
// cout<<p2->xishu<<"p2 "<<p2->zhishu<<endl;
}
if(p1->xishu==0)
{
// cout<<"come to ==0";
p1=p1->next;
p2=p2->next;
}
}
else
{

         //  cout<<"come to p1>p2"<<endl;
    s=p2->next;

             lc->next=p2;
lc=p2;
lc->next=NULL;
p2=s;
}
}
if(p1!=NULL) lc->next=p1;
if(p2!=NULL) lc->next=p2;
return LC;

}

int main()

{
linknode*head1,*head2,*head3;
int n1,n2,t;
cin>>t;
while(t--){
cin>>n1;

   head1=create(n1,head1);

   display(head1);

   cin>>n2;

   head2=create(n2,head2);

   display(head2);

   head3=addlink(head1,head2,head3);

   display(head3->next);
}
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息