-
总时间限制:
- 1000ms 内存限制:
- 65536kB
-
描述
-
使用带头结点的单链表存储一个多项式,设计多项式加法、乘法及显示多项式的算法。
提示:
1)使用带头结点单链表存储表示一个多项式,多项式结点按指数降序链接;
2)结点可以如下定义:
struct Node{
int exp; //指数
int coef; //系数
struct Node *next;
};
typedef Node* Poly;
2)设计函数Poly add(const Poly & A,const Poly & B)完成两个多项式的加法运算;
3)设计函数Poly mul(const Poly & A,const Poly & B)完成两个多项式的乘法运算;
4)设计函数void printPolynomial(const Poly &)显示输出一个多项式。
5)要求在main函数中进行测试。
6)多项式3x5-7x+6用一个整数序列表示为:3 5 -7 1 6 0 0 0,多项式项的指数<=100。< span="">
输入
- 两行,每行表示一个多项式,按多项式的指数降序输入,一个多项式的输入用0 0表示结束 输出
-
两行
第一行为多项式的加
第二行为多项的乘
输出形式形如3x^5-7x+6
样例输入
-
3 5 -7 1 6 0 0 0 -4 5 2 2 7 1 2 0 0 0
样例输出
-
-x^5+2x^2+8 -12^10+6x^7+49x^6-18x^5-14x^3-37x^2+28x+12
-
//Wrote by 齐大jmh #include<iostream> using namespace std; struct node{ int zhi; int xi; node *next; }; void input(node *p); node* sum(node *p,node *u); node* mult(node *p,node *u); void print(node *p); int main(){ struct node *a=new node; input(a); struct node *b=new node; input(b); print(sum(a,b)); //mult(a,b); print(mult(a,b)); return 0; } void input(node *p) { p->next=NULL; node *u=new node; while(cin>>u->xi>>u->zhi) { if(u->xi==0)break; p->next=u; u->next=NULL; p=u; u=new node; } } node* sum(node *p,node *u) { node *a,*b,*l; node *h=new node; h->next=NULL; l=h; a=p->next;b=u->next; while(a!=NULL&&b!=NULL) { if(a->zhi>b->zhi) { node *m=new node; m->zhi=a->zhi; m->xi=a->xi; m->next=NULL; l->next=m; l=m; a=a->next; } else if(a->zhi<b->zhi) { node *m=new node; m->zhi=b->zhi; m->xi=b->xi; m->next=NULL; l->next=m; l=m; b=b->next; } else { if(a->xi+b->xi!=0) { node *m=new node; m->xi=a->xi+b->xi; m->zhi=a->zhi; m->next=NULL; l->next=m; l=m; b=b->next; a=a->next; } else { b=b->next; a=a->next; } } } if(a==NULL&&b!=NULL){ while(b!=NULL) { node *m=new node; m->xi=b->xi; m->zhi=b->zhi; m->next=NULL; l->next=m; l=m; b=b->next; } } else if(a!=NULL&&b==NULL){ while(a!=NULL) { node *m=new node; m->xi=a->xi; m->zhi=a->zhi; m->next=NULL; l->next=m; l=m; a=a->next; } } return h; } node* mult(node *p,node *u) { int i=0; node *a=p->next,*b=u->next,*d; node *t=new node; t->next=NULL; d=t; node *y=new node; node *r=new node; r->zhi=0; r->xi=0; r->next=NULL; y->next=r; while(a!=NULL) { b=u->next; d=t; while(b!=NULL) { node *c=new node; c->zhi=a->zhi+b->zhi; c->xi=a->xi*b->xi; c->next=NULL; d->next=c; d=c; b=b->next; } //print(t); y=sum(y,t);//ÕâÀï³ö´í //print(sum(g,t)); a=a->next; } return y; } void print(node *p) { node *u; for(u=p->next;u!=NULL;u=u->next) { if(u->xi!=1&&u->xi!=-1&&u->xi!=0)cout<<u->xi; else if(u->xi==-1)cout<<"-"; else if(u->zhi==0&&u->xi!=0)cout<<u->xi; if(u->zhi>1)cout<<"x^"<<u->zhi; else if(u->zhi==1)cout<<"x"; if(u->next!=NULL&&u->next->xi>0)cout<<"+"; } cout<<endl; } //注意输出格式