一个关于多项式链表的程序,但乘法不能运行,请大家帮忙看看
这是本人写的一个关于多项式链表的加减乘运算的程序,但是乘法不能运行(编译和链接都没问题),请大家多多指教,小弟先谢谢了!!!# include<iostream>
using namespace std;
struct node
{
float coef;//系数域
int exp;//指数域
struct node * next;//指向下一个节点的指针
};
typedef struct node polynode;
polynode *add_polynode(polynode *pa,polynode *pb)//10
{
polynode *r1=NULL,*r2=NULL,*q1=NULL,*q2=NULL;
if(pb->next==NULL) return pa;//每个多项式链表至少有一个结点,它的系数和指数都是零
else if(pa->next==NULL)return pb;
else if(pa->next!=NULL&&pb->next!=NULL)
{
polynode head1,head2;
head1.next=pa;
head2.next=pb;
pa=&head1;//20
pb=&head2;
r1=pa,r2=pb;
q1=r1->next ;
q2=r2->next ;
do {
if(q1->exp >q2->exp )
{
r1=q1;
q1=q1->next ;
}//30
else if(q1->exp <q2->exp )
{
r1->next =q2;
q2=q2->next;
r1->next->next=q1;
r1=r1->next;
}
else if(q1->next ==q2->next )
{
float v;//40
v=q1->coef+q2->coef;
if(v)
{
q1->coef=v;
r1=q1;
q1=q1->next;
r2=q2;
q2=q2->next;
delete r2;
}//50
else{
q1=q1->next;
delete r1->next;
r1->next=q1;
r2=q2;
q2=q2->next;
delete r2;
}
}
}while(q1->next&&q2->next);//60
pa=head1.next;
if(q2->next ==NULL)delete q2;
else {
delete q1;
r1->next =q2;
}
return pa;
}
}//70
polynode *init_polynode()
{
int e=0;
float c=0;
polynode *p=NULL,*q=NULL,*r=NULL;
p=new polynode;//p指向的是链表的表头
r=p;//r指向链表的最后一个结点
r->next=NULL;
cout<<"请输入系数(实数型)和指数(整数型),注意:首项系数不要为零,按降幂方式输入当系数和指数为零时输入结束"<<endl;
//当输入的系数和指数为零时,表示输入过程结束,且输入按降幂方式输入//80
cin>>c>>e;
r->coef=c;
r->exp=e;
if(c==0) return p;
while(c!=0)
{
q=new polynode;//q指向每一次新产生的结点
cout<<"请输入次项系数coef(实数型)和指数exp(整数型)"<<endl;
cin>>c>>e;
q->coef=c;//90
q->exp=e;
q->next=NULL;
r->next=q;
r=q;
}
if(r->next!=NULL)r->next=NULL;
return p;
}//建立一个多项式链表,该链表的最后一个结点中方的系数和指数都是零
void print_polynode(polynode *q)
{ //100
if(q->coef==0)cout<<"f(x)=0"<<endl;
else
{
polynode *r=q;
cout<<"f(x)=";
while(r!=NULL&&r->coef !=0)
{
cout<<r->coef<<"X^"<<r->exp;
r=r->next ;
if(r->next !=NULL)//110
{
if(r->coef >=0)cout<<"+";
}
};
cout<<endl;
};
}//多项式的输出函数,吧多项式输出到屏幕上
polynode *posit_polynode(polynode*p)
{
if(p->coef ) //120
{
polynode *r=p;
while(r->next )
{
r->coef =-(r->coef) ;
r=r->next ;
}
}
return p;
}//求负的f(x)//130
polynode *minus_polynode(polynode*pa,polynode*pb)
{
return add_polynode(pa,posit_polynode(pb));
}//两多项式相减
polynode *nod_ml_nod(polynode *r1,polynode *r2)
{
while(r1->next &&r2->next )
{
r1->coef *=r2->coef ;
r1->exp +=r2->exp ;//140
delete r2;
return r1;
}
r1->coef =0;
r1->exp =0;
r1->next =NULL;
return r1;
}//实现两个多项式两项相乘,即链表的两个节点相乘
polynode *multip_polynode(polynode *pa,polynode *pb)//150
{ polynode *g=NULL,termin;
termin.coef =0;
termin.exp =0;
termin.next =NULL;
g=&termin;
if(pa->next &&pb->next )
{
polynode *ra=pa,*rb=NULL,*t=NULL,*s=NULL,*f=NULL,end;
end.coef =0;
end.exp =0;
end.next =NULL;
while(ra->next)//表示ra没有指到最后一个结点
{
f=&end;
rb=pb;
while(rb->next )
{
t=rb->next ;
s=nod_ml_nod(ra,rb);
f=add_polynode(f,s);
rb=t;
}
g=add_polynode(g,f);
}
return g;
}
else return g;
}//实现两多项式相乘
int main()
{
polynode *p=NULL,*q=NULL;
p=init_polynode();
q=init_polynode();
print_polynode(multip_polynode(p,q));
return 0;
}