C++ 队列 实现 多项式 加减法

#include <iostream>
#include <queue>


using namespace std;


struct Node
{
int exp;//指数
int coef;//系数
};


class Polynomial
{
public:
insert(int i,int j);
show();
    void sum(const Polynomial a,const Polynomial b);//加
void sub(const Polynomial a,const Polynomial b);//减
private:
queue<Node> m_queue;


};
Polynomial::insert(int i,int j)
{
Node node;
node.exp=j;//指数
node.coef=i;//系数
m_queue.push(node);
}
void Polynomial::sum(const Polynomial a,const Polynomial b){
Node n1,n2;


queue<Node> q1=a.m_queue;//
queue<Node> q2=b.m_queue;


while(q1.size()>0||q2.size()>0){
n1=q1.front();
n2=q2.front();
if(n1.exp>n2.exp){
q1.pop();
m_queue.push(n1);
  
}
else if(n1.exp<n2.exp){
q2.pop();
m_queue.push(n2);
}

else{
n1.coef+=n2.coef;
m_queue.push(n1);
q2.pop();
q1.pop();
}

}
}
void Polynomial::sub(const Polynomial a,const Polynomial b){
Node n1,n2;


queue<Node> q1=a.m_queue;//
queue<Node> q2=b.m_queue;


while(q1.size()>0||q2.size()>0){
n1=q1.front();
n2=q2.front();
if(n1.exp>n2.exp){
q1.pop();
m_queue.push(n1);
 
}
else if(n1.exp<n2.exp){
q2.pop();
m_queue.push(n2);

}
else{
n1.coef-=n2.coef;
m_queue.push(n1);
q2.pop();
q1.pop();
}
}
}


Polynomial::show(){
Node nodeFromQueue;
while(m_queue.size()>0){
nodeFromQueue=m_queue.front();
if(m_queue.size()==1){
cout<<nodeFromQueue.coef<<"~"
<<nodeFromQueue.exp;
m_queue.pop();
}
else{
cout<<nodeFromQueue.coef<<"~"
<<nodeFromQueue.exp<<"+";
m_queue.pop();
}
}
cout<<endl<<endl;
}


void main()
{
Polynomial a,b,c,d;
int i=0,j=0;//i为系数,j为指数
cout<<"第一个多项式(以-1结束):"<<endl;
while(true){
cin>>i>>j;
if(i==-1)
break;
else
a.insert(i,j);
}


cout<<endl;
cout<<"第二个多项式(以-1结束):"<<endl;
while(true){
cin>>i>>j;
if(i==-1)
break;
else
b.insert(i,j);
}
cout<<"相加:"<<endl;
c.sum(a,b);
d.sub(a,b);
cout<<endl;
a.show();
b.show();
c.show();
d.show();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值