- 问题描述
一元多项式每一项由系数Pi及x的指数i组成。若多项式按照升幂排列,则它由n+1个系数唯一确定,因此可以用一个线性表表示,其指数i隐藏在系数Pi的序号内。分别两个多项式A(x)、B(x)系数、指数所构成的表。输出为两多项式和C(x)所构成的链表。
- 设计思路
将B(x)加到A(x)后,形成C(x)。带有头结点的线性链表表示多项式A(x)、B(x),ha、hb分别指向A(x)、B(x)的头指针,p、q分别指向多项式第一项。比较p、q结点的指数项若p结点指数项小q结点指数项,则p所指结点为C(x)一项,p后移一个结点;若p指数项大于q指数项,则q所指结点为C(x)一项。若相等,则系数相加,为零则删去,否则修改系数并回收。所用变量包括线性链表头指针ha、hb,指针p、q。算码描述:
ADD(ha,hb)
- p<-next(ha);q<-next(hb)
- pre<-ha;hc<_ha //pre指向p的前驱,hc为C(x)头指针
- while(p!=nil)AND (q!=nil) do
- case
- EXP(p)<EXP(q):
- {pre<-p; p<-next(p)}
- EXP(p)=EXP(q):
- {X<-COFE(p)+COFE(q);
- If(x!=0) then {COFE(p)<-x;pre<-q}
- Else {next (pre)<-next(p);RET(p)}
- P<-next(pre);u<-q;q<-next(q);RET(u)}
- EXP(p)>EXP(q):
- {u<-next(q); next(q)<-p;next(pre)<-q;pre<-q;q<-u}
- End(case)
- End(while)
- If(q!=nil) then next (pre)<-q
- RET(hb) //释放多项式B(x)头结点//
- Return
- 测试用例及结果说明
测试用例:A(x)=3x+5x^12+6x^64; B(x)=4x+4x^10+7x^128
测试结果:C(x)=7x+4x^10+5x^12+6x^64+7x^128
- 设计及测试过程
第一步:提出问题;
第二步:问题转换;
第三步:算法构思;
第四步:伪码描述;
第五步:代码编写;
第六步:代码测试;
第七步:代码修正;
参考书籍:《计算机软件技术基础》 清华大学出版社 第三版
- 评价和改进
算法优点:链式存储形式节约了大量空间。
算法缺点:算法实质是将B(x)加到A(x)之后,运算结束后丢失了初始数据。
- 心得体会
软件技术的学习需要实践的积累,在实际的编写之中可以领悟到软件工程师的思维模式和工作过程,有利于工程思想的培养。
#include<iostream>
using namespace std;
struct node
{
int exp;
float coef;
struct node *next;
}*ha,*hb;
void print(struct node *head)
{
struct node *p;
p=head->next;
while(p->next!=NULL)
{
cout<<p->coef<<"X"<<p->exp<<"+";
p=p->next;
}
cout<<p->coef<<"X"<<p->exp;
}
int main()
{
int exp;
float coef;
struct node *tail,*newnode;
cout<<"请输入第一个多项式的系数和次数(结束输入请输入‘0’)"<<endl;
ha=new node;
tail=ha;
while(1)
{
cin>>coef;
if(coef==0)
break;
cout<<"X";
cin>>exp;
cout<<"+";
newnode=new node;
newnode->coef=coef;
newnode->exp=exp;
tail->next=newnode;
tail=newnode;
}
tail->next=NULL;
cout<<"请输入第二个多项式的系数和次数(结束输入请输入‘0’)"<<endl;
hb=new node;
tail=hb;
while(1)
{
cin>>coef;
if(coef==0)
break;
cout<<"X";
cin>>exp;
cout<<"+";
newnode=new node;
newnode->coef=coef;
newnode->exp=exp;
tail->next=newnode;
tail=newnode;
}
tail->next=NULL;
print(ha);
cout<<"+";
print(hb);
cout<<"=";
float x;
struct node *p=ha->next;
struct node *q=hb->next;
struct node *pre=ha;
struct node *hc=ha;
struct node *u;
while(p!=NULL&&q!=NULL)
{
if(p->exp<q->exp)
{
pre=p;
p=p->next;
}
else if(p->exp==q->exp)
{
x=p->coef+q->coef;
if(x!=0)
{
p->coef=x;
pre=p;
}
else
pre->next=p->next;
p=pre->next;
u=q;
q=q->next;
}
else if(p->exp>q->exp)
{
u=q->next;
q->next=p;
pre->next=q;
pre=q;
q=u;
}
}
if(q!=NULL)
pre->next=q;
print(ha);
cout<<endl;
system("pause");
return 0;
}