#include<stdio.h>
#include<iostream>
using namespace std;
struct Node
{
int a;//系数
int m;//指数
Node* next;
};
class cla
{
int n;
Node* head;
public:
cla();
void Init();
cla(cla & pt);
//~cla();
cla operator +(cla & pt);
void print();
};
cla::cla()
{
n=0;
head=0;
}
void cla::Init()
{
int i,aa,mm;
Node * temp;
Node * head1;
cout<<"构造一元多项式:"<<endl;
cout<<"请输入多项式的项数:";
cin>>n;
for (i=1;i<=n;i++)
{
cin>>aa;
cin>>mm;
temp=new Node;
temp->a=aa;
temp->m=mm;
temp->next=NULL;
if (i==1)
{
head=temp;
head1=head;
}
else
{
head1->next=temp;
head1=temp;
}
}//for i
head1=head;
cout<<"n="<<n<<"P=";
while(head1->next!=NULL)
{
cout<<head1->a<<"x^"<<head1->m<<"+";
head1=head1->next;
}//while
cout<<head1->a<<"x^"<<head1->m<<endl;
}//cla()
cla::cla(cla & pt)
{
n=pt.n;
head=pt.head;
}//copy construction
//cla::~cla()
//{
// Node * head1;
// head1=head;
// cout<<"P=";
// while(head1->next!=NULL)
// {
// cout<<head1->a<<"x^"<<head1->m<<"+";
// head1=head1->next;
// }//while
// cout<<head1->a<<"x^"<<head1->m<<endl;
//}//~cla()
cla cla::operator +(cla & pt)
{
cla temp;
int count=0;
Node * head1;
Node * head2;
Node * head3;
Node * node;
temp.head=NULL;
head1=head;
head2=pt.head;
while(head1!=NULL && head2!=NULL)
{
node=new Node;
if (head1->m<head2->m)
{
node->a=head1->a;
node->m=head1->m;
node->next=NULL;
if (temp.head==NULL) {temp.head=node;head3=temp.head;} else {head3->next=node;head3=node;}
head1=head1->next;
count++;
}
else if (head1->m>head2->m)
{
node->a=head2->a;
node->m=head2->m;
node->next=NULL;
if (temp.head==NULL) {temp.head=node;head3=temp.head;} else {head3->next=node;head3=node;}
head2=head2->next;
count++;
}
else if (head1->m==head2->m)
{
if (head1->a+head2->a!=0)
{
node->a=head1->a+head2->a;
node->m=head1->m;
node->next=NULL;
if (temp.head==NULL) {temp.head=node;head3=temp.head;} else {head3->next=node;head3=node;}
head2=head2->next;
head1=head1->next;
count++;
}
else
{
head2=head2->next;
head1=head1->next;
}
}//if
}//while
if (head1==NULL && head2!=NULL)
{
while(head2!=NULL)
{
node=new Node;
node->a=head2->a;
node->m=head2->m;
node->next=NULL;
if (temp.head==NULL) {temp.head=node;head3=temp.head;} else {head3->next=node;head3=node;}
head2=head2->next;
count++;
}//while()
}
else if (head2==NULL && head1!=NULL)
{
node=new Node;
node->a=head1->a;
node->m=head1->m;
node->next=NULL;
if (temp.head==NULL) {temp.head=node;head3=temp.head;} else {head3->next=node;head3=node;}
head1=head1->next;
count++;
}//if
temp.n=count;
return temp;
}//cla operator +(cla & pt)
void cla::print()
{
Node * head1;
head1=head;
//cout<<"P=";
if (n==0)
{
cout<<"空多项式"<<endl;
return ;
}//if
while(head1->next!=NULL)
{
cout<<head1->a<<"x^"<<head1->m<<"+";
head1=head1->next;
}//while
cout<<head1->a<<"x^"<<head1->m<<" ("<<n<<")"<<endl;
}//print
main()
{
cla pa,pb,pc;
int select;
cout<<"请选择:";
cin>>select;
while(select)
{
pa.Init();
pb.Init();
pc.Init();
cout<<"Pa+Pb=";
(pa+pb).print();
cout<<"Pa+Pb+Pc=";
(pa+pb+pc).print();
cout<<"请选择:";
cin>>select;
}
}