using namespace std;
class mploy
{
public:
mploy *next;
mploy *creat(char);
void addploy(mploy *,mploy *);
void print(mploy *);
private:
int coef;
int expn;
};
int n;
mploy *mploy::creat(char ch)
{
mploy *head,*p1,*p2;
n=0;
p1=p2=new mploy;
cout<<"Input多项式的系数和指数"<<endl;
cin>>p1->coef>>p1->expn;
head=NULL;
while(p1->coef!=0)
{
n=n+1;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=new mploy;
cin>>p1->coef>>p1->expn;
}
p2->next=NULL;
return head;
}
void mploy::addploy(mploy *a,mploy *b)
{
mploy *ha,*hb,*p,*q;
ha=a;
hb=b;
int x;
p=a->next;
q=b->next;
while(p!=NULL&&q!=NULL)
{
if(p->expn<q->expn)
{
ha=p;
p=p->next;
}
else if(p->expn==q->expn)
{
x=p->coef+q->coef;
if(x!=0)
{
p->coef=x;
ha=p;
}
else
{
ha->next=p->next;
}
hb->next=q->next;
q=hb->next;
p=ha->next;
}
else
{
hb=q->next;
q->next=p;
ha->next=q;ha=q;q=hb;
}
}
if (q!=NULL)
ha->next=q;
}
void mploy::print(mploy *h)
{
mploy *t;
t=h;
if(h!=NULL)
if(t->coef!=0)
{
if(t->expn!=0)
cout<<t->coef<<"x^"<<t->expn;
else
cout<<t->coef;
}
while(t!=NULL)
{
if(t->coef>0)
cout<<"+";
cout<<t->coef<<"x^"<<t->expn;
t=t->next;
}
cout<<endl;
}
void main()
{
mploy *a,*b;
mploy c;
a=c.creat('A');
cout<<"A=";
c.print(a);
b=c.creat('B');
cout<<"B=";
c.print(b);
c.addploy(a,b);
cout<<"M=";
c.print(a);
}
运行时是“
Input多项式的系数和指数
1 1 2 2 3 3 0 0
A=1x^1+1x^1+2x^2+3x^3
Input多项式的系数和指数
2 1 3 2 4 3 0 0
B=2x^1+2x^1+3x^2+4x^3
M=1x^1+1x^1+5x^2+7x^3
后面就能正确输出,前面就不行,不知道为什么要重复输出一个项,
请帮我看看 谢谢了