/********************* title: 一元多项式相加 author: jay chang date: 2009.4.12 ******************** #include<stdlib.h> #include<iostream> using namespace std; typedef struct poly{ int coef; int exp; poly * next; }poly,* Head; int count; //创建一个一元多项式 poly * createPoly() { Head head=(poly*)malloc(sizeof(poly)); int coef,exp; head->coef=-1;head->exp=-1; poly *p=head; cin>>coef;cin>>exp; while(coef!=-1&&exp!=-1) { poly *item=(poly*)malloc(sizeof(poly)); item->coef=coef; item->exp=exp; cin>>coef;cin>>exp; p->next=item; p=p->next; } p->next=NULL; return head; } //将两个一元多项式相加 poly * addPoly(poly * ployA,poly * polyB) { count=1; Head head=(poly *)malloc(sizeof(poly)); poly * pos=head,*temp; pos->coef=-1;pos->exp=-1; poly * pA= ployA->next; poly * pB= polyB->next; while(pA!=NULL&&pB!=NULL) { if(pA->exp<pB->exp){ pos->next=pA; pA=pA->next; pos=pos->next; } else if(pA->exp>pB->exp){ pos->next=pB; pB=pB->next; pos=pos->next; } else if(pA->exp==pB->exp){ int sum=pA->coef+pB->coef; if(sum==0){ pA=pA->next; pB=pB->next; } else{ pA->coef=sum; pos->next=pA; pos=pos->next; pA=pA->next; pB=pB->next; } } count++;//一元二次方程的长度计数器 } while(pA!=NULL)//如果pA多项式还有项 { pos->next=pA; pos=pos->next; pA=pA->next; count++; } while(pB!=NULL)//如果pB 多项式还有项 { pos->next=pB; pos=pos->next; pB=pB->next; count++; } return head; } //打印一元多项式 void procOutput(Head head) { poly * p=head->next; int length=1; cout<<"f(x)="; while(p!=NULL){ //cout<<length<<" "<<count<<"\n"; if(length==5) { //如果是最后一个元素 if(p->exp==0) cout<<p->coef<<"\n"; else cout<<p->coef<<"*x^"<<p->exp<<"\n"; } else if(length!=count) { //不是最后一个元素 if(p->coef==0) cout<<p->coef<<"+"; else cout<<p->coef<<"*x^"<<p->exp<<"+"; } p=p->next;length++; } } int main() { poly * polyA,* polyB; polyA=createPoly(); polyB=createPoly(); Head head=addPoly(polyA,polyB); procOutput(polyA); return 0; } /* 使用方法: 例如要输入f(x)=3*x+4*x+7*x^3+6*x^4; g(x)=7*x+8*x^4+9*x^6; 则只要输入 3 0 4 1 7 3 6 4 -1 -1 (表示一个多项式输入结束) 7 1 8 4 9 6 -1 -1 */
一元多项式相加
最新推荐文章于 2023-04-16 02:32:32 发布