例题2-11:请设计算法,实现一元多项式的相加运算。
#include<stdio.h>
#include<string.h>
using namespace std;
typedef struct PNode{
int coef;
int exp;
struct PNode *next;
PNode(int Coef=0,int Exp=-1,PNode *Next=NULL){
coef=Coef;exp=Exp;next=Next;
}
}PNode,*PolyList;
void OutputPolyList(PolyList &L){
PolyList p=L->next;
printf("f(x)=");
if(p->coef==1){
printf("x^(%d)%c",p->exp,p->next?' ':'\n');
}else{
printf("%dx^(%d)%c",p->coef,p->exp,p->next?' ':'\n');
}
p=p->next;
while(p){
if(p->coef==1){
printf("x^(%d)%c",p->exp,p->next?' ':'\n');
}else{
printf("%+dx^(%d)%c",p->coef,p->exp,p->next?' ':'\n');
}
p=p->next;
}
}
void InitPolyList(PolyList &L){
PolyList p,Pre;
L=new PNode(0,-1,NULL);
Pre=L;
int n,Exp;
int Coef;
printf("请输入n的值:\n");
scanf("%d",&n);
printf("依次输入n项:\n");
for(int i=1;i<=n;i++){
printf("第%d项:\n",i);
printf("指数:");scanf("%d",&Exp);
printf("系数:");scanf("%d",&Coef);
printf("Exp : %d Coef:%d\n",Exp,Coef);
p=new PNode(Coef,Exp,NULL);
Pre->next=p;
Pre=p;
}
}
void AddPolyList(PolyList &Pa,PolyList &Pb){
PolyList Pre=Pa,pa=Pa->next,pb=Pb->next,s;
while(pa&&pb){
if( pa->exp < pb->exp ){
Pre=pa; pa=pa->next;
}else if( pa->exp > pb->exp ){
Pre->next=pb;
Pre=pb; pb=pb->next;
Pre->next=pa;
}else{
int x=pa->coef + pb->coef;
if(x){
pa->coef=x; Pre=pa;
}else{
Pre->next=pa->next;
delete pa;
}
s=pb; pb=pb->next; delete s;
pa=Pre->next;
}
}
if(pb) {
Pre->next=pb;
}
delete(Pb);
}
int main(){
PolyList Pa,Pb;
InitPolyList(Pa);
printf("Pa:\n");
OutputPolyList(Pa);
InitPolyList(Pb);
printf("Pb:\n");
OutputPolyList(Pb);
printf("Pa+Pb:\n");
AddPolyList(Pa,Pb);
OutputPolyList(Pa);
return 0;
}