#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
typedef struct PolyNode {
int coef;
int exp;
PolyNode *next;
}node;
node * CreatPoly(){
PolyNode *h,*tail,*s;
int coef,exp;
h=( PolyNode *)malloc(sizeof(node));
h->next=NULL;
tail=h;
cout<<"coef,exp: ";
scanf("%d,%d",&coef,&exp);
while (coef){
PolyNode *s=( PolyNode *)malloc (sizeof(node));
s->coef=coef;
s->exp=exp;
s->next=tail->next;
tail->next=s;
tail=s;
cout<<"coef,exp: ";
scanf("%d,%d",&coef,&exp);
}
return h;
}
void PolyAdd(node *Polya,node *Polyb){
node *p,*q,*pre,*temp;
p=Polya->next;
q=Polyb->next;
pre=Polya;
int sum;
while (p&&q){
if(p->exp < q->exp){
pre->next = p;
pre = p;
p = p->next;
}else if(p->exp > q->exp){
pre->next = q;
pre = q;
q = q->next;
}
else{
sum=p->coef + q->coef ;
if(sum){
p->coef=sum;
pre->next=p;
pre=p;
p=p->next;
temp=q->next;
free(q);
q=temp;
}else{
temp=p->next;
free(p);
p=temp;
temp=q->next;
free(q);
q=temp;
}
}
}
pre->next = p ? p:q;
}
int PrintPoly(node *h){
node *p=h->next;
while (p){
printf("%d*x^%d ",p->coef,p->exp);
p=p->next;
}
cout<<endl;
return 1;
}
int main()
{
node *Polya,*Polyb;
cout<<"请输入第一个一元多项式的系数和指数(假定以输入系数为0来结束)"<<endl;
Polya= CreatPoly();
cout<<"请输入的第一个一元多项式为"<<endl;
PrintPoly(Polya);
cout<<"请输入第二个一元多项式的系数和指数(假定以输入系数为0来结束)"<<endl;
Polyb= CreatPoly();
cout<<"请输入的第二个一元多项式为"<<endl;
PrintPoly(Polyb);
cout<<"这两个一元多项式相加后的结果为"<<endl;
PolyAdd(Polya,Polyb);
PrintPoly(Polya);
return 0;
}
用链式线性表实现两个一元多项式相加
最新推荐文章于 2022-01-17 18:00:39 发布