一道普通的大作业题我竟然折腾了这么久,汗颜啊!
#include <iostream>
using namespace std;
class Poly;
class node
{
private:
int coef;//系数
int exp;//指数
node *next;
friend Poly;
friend void calculate(Poly &x,Poly &y);
};
class Poly
{
private:
node* head;
public:
void creat();
void print();
void Delete();
node* Returnhead();
void print2();
};
void Poly::creat()
{
node *tail,*p;
int a,b;
cout<<"请输入多项式"<<endl;
p=new node;
p->exp=0;
p->coef=0;
p->next=NULL;
head=tail=p;
while(cin>>a>>b&&b>0)
{
p=new node;
p->coef=a;
p->exp=b;
p->next=NULL;
tail->next=p;
tail=p;
}
}
node* Poly::Returnhead()
{
if (head->next)
return head;
else
return NULL;
}
void calculate(Poly &x,Poly &y)
{
node *p1,*p,*q,*temp;
p1=x.Returnhead();
p=p1->next;
q=y.Returnhead()->next;
while(q&&p)
{
if (p->exp==q->exp)
{
p->coef+=q->coef;
if (p->coef==0)
{
p1->next=p->next;
delete(p);
p=p1->next;
}
else
{
p1=p;
p=p->next;
}
q=q->next;//不管怎么样,q1都要向后移
}
else
if (p->exp<q->exp)
{
temp=new node;
temp->coef=q->coef;
temp->exp=q->exp;
p1->next=temp;
temp->next=p;
q=q->next;
}
else
{
p1=p;
p=p->next;
}
}
while(q)
{
node*temp;
temp=new node;
temp=q;
p1->next=temp;
p1=temp;
q=q->next;
}
}
void Poly::print()
{
node*p;
p=head->next;
if (p->coef==1)
cout<<"x"<<'^'<<p->exp;
else
if (p->coef==-1)
cout<<"-x"<<'^'<<p->exp;
else
if (p->coef==0)
p=p->next;
else
cout<<p->coef<<'x'<<'^'<<p->exp;
p=p->next;
while(p)
{
if (p->coef==1)
cout<<'+'<<'x'<<'^'<<p->exp;
else
if (p->coef==-1)
cout<<"-x"<<'^'<<p->exp;
else
if (p->coef==0)
p=p->next;
else
if (p->coef>0)
cout<<'+'<<p->coef<<'x'<<'^'<<p->exp;
else
cout<<p->coef<<'^'<<p->exp;
p=p->next;
}
}
void Poly::print2()
{ node *p;
p=head->next;
while(p)
{
if (p->coef==1)
cout<<'+'<<'x'<<'^'<<p->exp;
else
if (p->coef==-1)
cout<<"-x"<<'^'<<p->exp;
else
if (p->coef==0)
p=p->next;
else
if (p->coef>0)
cout<<'+'<<p->coef<<'x'<<'^'<<p->exp;
else
cout<<p->coef<<'^'<<p->exp;
p=p->next;
}
}
void Poly::Delete()
{
node *p=head,*q;
while(p)
{
q=p->next;
delete(p);
p=q;
}
cout<<"内存已释放成功"<<endl;
}
int main()
{
Poly A,B;
A.creat();
cout<<"A的表达式为:";
A.print();
cout<<endl;
B.creat();
cout<<"B的表达式为:";
B.print();
cout<<endl;
cout<<"计算的多项式结果为:"<<endl;
A.print();
B.print2();
cout<<"=";
calculate(A,B);
if (A.Returnhead()==NULL)
cout<<0<<endl;
else
A.print();
cout<<endl;
A.Delete();
return 0;
}