实现:
/*********************************
多项式加法
by Rowandjj
2014/4/6
*********************************/
#include<IOSTREAM>
using namespace std;
typedef struct _POLYNNODE_
{
int coef;//系数
int expn;//指数
struct _POLYNNODE_ *next;
}PolynNode,*PolynList;
void initPolynList(PolynList &L);
void CreatePolyn(PolynList &L,int n);//创建一元多项式
void PolynTraverse(PolynList L,void (*vi)(int,int));//遍历
void AddPolyn(PolynList &La,PolynList &Lb,PolynList &Lc);//用Lc返回相加后的一元多项式
void visit(int e1,int e2);
int main()
{
PolynList La,Lb,Lc;
initPolynList(La);
initPolynList(Lc);
CreatePolyn(La,2);
cout<<"la = ";
PolynTraverse(La,visit);
cout<<endl;
initPolynList(Lb);
CreatePolyn(Lb,2);
cout<<"Lb = ";
PolynTraverse(Lb,visit);
cout<<endl;
AddPolyn(La,Lb,Lc);
PolynTraverse(Lc,visit);
return 0;
}
void initPolynList(PolynList &L)
{
L = (PolynList)malloc(sizeof(PolynNode));
if(!L)
{
exit(-1);
}
L->next = NULL;
}
void CreatePolyn(PolynList &L,int n)
{
int i;
int coef,expn;
PolynList p = L,q;
if(n<=0)
{
return;
}
for(i = 0; i < n; i++)
{
q = (PolynList)malloc(sizeof(PolynNode));
if(!q)
{
exit(-1);
}
cin>>coef;
cin>>expn;
q->coef = coef;
q->expn = expn;
p->next = q;
p = p->next;
}
p->next = NULL;
}
void PolynTraverse(PolynList L,void (*vi)(int,int) )
{
PolynList p = L->next;
while(p)
{
vi(p->coef,p->expn);
if(p->next)
{
cout<<"+";
}
p = p->next;
}
cout<<endl;
}
void visit(int e1,int e2)
{
cout<<e1<<"x^"<<e2;
}
void AddPolyn(PolynList &La,PolynList &Lb,PolynList &Lc)
{
PolynList pa,pb,pc;
pa = La->next;
pb = Lb->next;
pc = Lc = La;
while(pa&&pb)
{
if(pa->expn < pb->expn)
{
pc->next = pa;
pc = pa;
pa = pa->next;
}else if(pa->expn > pb->expn)
{
pc->next = pb;
pc = pb;
pb = pb->next;
}else
{
pa->coef = pa->coef + pb->coef;
if(pa->coef != 0)
{
pc->next = pa;
pc = pa;
}
pa = pa->next;
pb = pb->next;
}
}
pc->next = pa ? pa : pb;
}