一元多项式问题

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

一元多项式相加问题

本实验的目的是进一步熟练掌握应用链表处理实际问题的能力。

一、问题描述:

一元多项式相加是通过键盘输入两个形如p0+p1*x^1+p2*x^2+pn*x^n的多项式,经过程序运算后在屏幕上输出它们的相加和。

二、数据结构设计:

分析任意一元多项式的描述方法可知,一个一元多项式的每一个子项都有“系数—指数”两部分组成,所以可以将它抽象成一个有“系数—指数对”构成的线性表,由于对多项式中系数为0的子项可以不记录它的指数值,对于这样的情况就不再付出存储空间来存放它了。基于这样的分析,可以采用一个带有头结点的单链表来表示一个一元多项式。具体数据类型定义为:

typedef struct node{

float coef;

int exp;

int flag;

struct node *next;

}PolyNode;

三、功能(函数)设计:

1、输入并建立多项式的功能模块

PolyNode * create(){

float A;

int B;

PolyNode *a=NULL;

PolyNode *b=NULL;

PolyNode *c=NULL;

scanf("%f,%d",&A,&B);

while(A!=0||B!=0){

if(A!=0){

c=new PolyNode;

c->coef=A;

c->exp=B;

c->flag=0;

c->next=NULL;

if(a==NULL){

a=c;

b=a;

}

else{

b->next=c;

b=c;

}

}

scanf("%f,%d",&A,&B);

}

return a;

}

2、多项式相加的功能模块

PolyNode *add(PolyNode *p,PolyNode *q){

PolyNode *x,*y;

PolyNode *r=NULL;

PolyNode *c=NULL;

PolyNode *l=NULL;

x=p;

y=q;

while(x&&y){

r=new PolyNode;

if(x->exp==y->exp){

r->coef=x->coef+y->coef;

r->exp=x->exp;

r->flag=0;

r->next=NULL;

x->flag=1;

y->flag=1;

x=x->next;

y=y->next;

}

else if(x->exp>y->exp){

r->coef=y->coef;

r->exp=y->exp;

r->flag=0;

r->next=NULL;

y->flag=1;

y=y->next;

}

else{

r->coef=x->coef;

r->exp=x->exp;

r->flag=0;

r->next=NULL;

x->flag=1;

x=x->next;

}

if(c==NULL){

c=r;

l=c;

}

else{

l->next=r;

l=r;

}

}

if(x==NULL)

x=y;

while(x){

r=new PolyNode;

r->coef=x->coef;

r->exp=x->exp;

r->flag=0;

r->next=NULL;

if(c==NULL){

c=r;

l=c;

}

else{

l->next=r;

l=r;

}

x->flag=1;

x=x->next;

}

return c;

}

3、多项式显示的功能模块

int print(PolyNode *w){

if(w==NULL){

cout<<'0';

return 0;

}

PolyNode *v;

v=w;

cout<<'(';

if(v->coef<0)cout<<'-';

cout<coef<<'x'<exp;

v=v->next;

while(v){

if(v->coef>=0)cout<<'+';

cout<coef<<'x'<exp;

v=v->next;

}

cout<<')';

}

四、界面设计:

注意提示用户每一步操作输入的格式和限制,指导用户按照正确的格式输入数据。如图:

五、编码实现:

#include

#include

using namespace std;

typedef struct node{

float coef;

int exp;

int flag;

struct node *next;

}PolyNode;

int print(PolyNode *w){

if(w==NULL){

cout<<'0';

return 0;

}

PolyNode *v;

v=w;

cout<<'(';

if(v->coef<0)cout<<'-';

cout<coef<<'x'<exp;

v=v->next;

while(v){

if(v->coef>=0)cout<<'+';

cout<coef<<'x'<exp;

v=v->next;

}

cout<<')';

}

PolyNode *add(PolyNode *p,PolyNode *q){ PolyNode *x,*y;

PolyNode *r=NULL;

PolyNode *c=NULL;

PolyNode *l=NULL;

x=p;

y=q;

while(x&&y){

r=new PolyNode;

if(x->exp==y->exp){

r->coef=x->coef+y->coef;

r->exp=x->exp;

r->flag=0;

r->next=NULL;

x->flag=1;

y->flag=1;

x=x->next;

y=y->next;

}

else if(x->exp>y->exp){

r->coef=y->coef;

r->exp=y->exp;

r->flag=0;

r->next=NULL;

y->flag=1;

y=y->next;

}

else{

r->coef=x->coef;

r->exp=x->exp;

r->flag=0;

r->next=NULL;

相关文档
最新文档