数据结构一元多项式相加问题
#include <iostream>using namespace std;
typedef struct node
{
float coef;//系数域
int exp;//指数域
struct node *next;
}polynode;
//创建
polynode *init_polynode()
{
int c=0,e=0;
polynode *p=NULL,*q=NULL,*r=NULL;
p=new polynode;
r=p;
cout<<"请按指数的升降次序输入系数和指数:"<<endl;
cin>>c>>e;
while(c!=0)
{
q=new polynode;
q->coef=c;
q->exp=e;
r->next=q;
r=q;
cin>>c>>e;
}
if(r!=NULL)
r->next=NULL;
return p;
}
void sort(polynode *L,int n){ //冒泡排序
polynode *p,*q;
p=L->next;
q=p->next;
int i,j,t,k;
for(j=0;i<n-1;j++)
{
for(i=0;i<n-j-1;i++)
{
if(p->exp>q->exp)
{
t=p->exp;
p->exp=q->exp;
q->exp=t;
k=p->coef;
p->coef=q->coef;
q->coef=k;
}//if
p=p->next;
q=q->next;
}//for
}//for
}//PaixuF
//相加
polynode *add_polynode(polynode *pa, polynode *pb)
{
polynode *head, *t, *s,*p1,*p2;
int v;
p1=pa->next;
p2=pb->next;
t=pa;
head=t;
while(p1&&p2)
{
if(p1->exp==p2->exp)
{
v=p1->coef+p2->coef;
if(v!=0)
{
p1->coef=v;
t->next=p1;
t=t->next;
p1=p1->next;
s=p2;
p2=p2->next;
delete s;
}
else
{
s=p1->next;delete p1;p1=s;
s=p2->next;delete p2;p2=s;
}
}
else if(p1->exp<p2->exp)
{
t->next=p1;
t=t->next;
p1=p1->next;
}
else
{
t->next=p2;
t=t->next;
p2=p2->next;
}
}
if(p1)
t->next=p1;
else
t->next=p2;
return head;
}
void print_polynode(polynode *head)
{
polynode *p=NULL;
p=head->next;
if(p==NULL)
cout<<"多项式为NULL;"<<endl;
else
{
while(p!=NULL)
{
if(p->coef>=0)
cout<<"+"<<p->coef<<"x^"<<p->exp;
else
cout<<p->coef<<"x^"<<p->exp;
p=p->next;
}
cout<<endl;
}
}
int main()
{
polynode *heada=NULL,*headb=NULL,*headsum=NULL;
int m,n;
cout<<"建立第一个函数:"<<endl;
cout<<"请输入多项式项数:";
cin>>m;
heada=init_polynode();
cout<<"第一个函数:"<<endl;
sort(heada,m);
print_polynode(heada);
cout<<"建立第二个函数:"<<endl;
cout<<"请输入多项式项数:";
cin>>n;
headb=init_polynode();
cout<<"第二个函数:"<<endl;
sort(headb,n);
print_polynode(headb);
headsum=add_polynode(heada,headb);
cout<<"函数和为:"<<endl;
print_polynode(headsum);
return 0;
}
我的这个程序当有一个多项式为0时不能输出结果,不知道该怎么改?