📄 一元多项式的加减.cpp
字号:
#include<iostream.h>
class mploy
{
public:
double coef;//多项式的系数
int exp;//多项式的指数
mploy *next;// 下一个元素的地址
public:
mploy *creatploy()//建立多项式链表
{
mploy *p,*r,*s;
p=r=new mploy;//申请头结点
double x;
int y;
cout<<"输入多项式的系数和指数(系数为0结束,指数从小到大)";
cin>>x>>y;
while(x)
{
s=new mploy;
s->coef=x;
s->exp=y;
r->next=s;
r=s;
cout<<"输入多项式的系数和指数(系数为0结束,指数从小到大)";
cin>>x>>y;
}
r->next=NULL;
return p;
}
void printploy(mploy *h)//输出多项式
{
mploy *p=h->next;//输出多项式的第一个结点
if(p->coef!=0){
if(p->exp!=0) cout<<p->coef<<"x^"<<p->exp;
else cout<<p->coef;
}
p=p->next;
while(p!=NULL) //输出多项式的其他结点
{
if (p->coef>0) cout<<"+";
cout<<p->coef<<"x^"<<p->exp;
p=p->next;
}
cout<<endl;
}
//多项式相加
void addploy(mploy *A,mploy *B)
{
mploy *p,*q,*pre,*C,*u;
p=A->next;q=B->next;
pre=A;C=A;
while (p!=NULL&&q!=NULL)
{
if(p->exp<q->exp)
{pre=p;p=p->next;}
else if(p->exp==q->exp)
{
double x=p->coef+q->coef;
if (x!=0){p->coef=x;pre=p;}
else{pre->next=p->next;delete p;}
p=pre->next;u=q;
q=q->next;delete u;
}
else
{
u=q->next;
q->next=p;
pre->next=q;
pre=q;q=u;
}
}
if(q!=NULL)pre->next=q;
//return C;
}
//多项式相减
void subploy(mploy *A,mploy *B)
{
mploy *p,*q,*pre,*C,*u;
p=A->next;q=B->next;
pre=A;C=A;
while (p!=NULL&&q!=NULL)
{
if(p->exp<q->exp)
{pre=p;p=p->next;}
else if(p->exp==q->exp)
{
double x=p->coef-q->coef;
if (x!=0){p->coef=x;pre=p;}
else{pre->next=p->next;delete p;}
p=pre->next;u=q;
q=q->next;delete u;
}
else
{
u=q->next;
q->next=p;
pre->next=q;
pre=q;q=u;
}
}
if(q!=NULL)pre->next=q;
}
};
void add()
{
mploy *A,*B,c;
cout<<"建立第一个多项式链表"<<endl;
A=c.creatploy(); //建立第一个多项式链表
cout<<"建立第2个多项式链表"<<endl;
B=c.creatploy();//建立第2个多项式链表
//c.printploy(A);//输出第1个多项式
//c.printploy(B);//输出第2个多项式
c.addploy(A,B);
//c.subploy(A,B);
c.printploy(A);//输出合并后的多项式
}
void sub()
{mploy *A,*B,c;
cout<<"建立第一个多项式链表"<<endl;
A=c.creatploy(); //建立第一个多项式链表
cout<<"建立第2个多项式链表"<<endl;
B=c.creatploy();//建立第2个多项式链表
//c.printploy(A);//输出第1个多项式
//c.printploy(B);//输出第2个多项式
//c.addploy(A,B);
c.subploy(A,B);
c.printploy(A);//输出合并后的多项式
}
void main()
{int i;
int a;
cin>>i;
while(i!=0)
{
cin>>a;
int c=a;
if (c=1){ add();}
else if(c=2){sub();}
cin>>i;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -