c++实现一元稀疏多项式加减

// 学习数据结构课程和自学c++库时所写。利用了c++标准库中的<list>以及系列操作,相关函数和操作都不是很熟悉,写了以后提高熟悉度。
// 代码都比较通俗易懂,所以注释比较少,核心算法为Add()函数的实现
// author:刘知安 
// time:2017/10/11
 
 
#include<iostream> 
 
#include<string>
#include<list>
using namespace std;
class polyNode{
public:
float coef; // 系数
int expn; // 指数
polyNode(float co, int ex)
{
coef = co;
expn = ex;
}
};
class Poly{
private:
list<polyNode> l;
public:
Poly();
~Poly();
void Add(Poly another); //加上另一个多项式
void Sub(Poly another); //减去另一个多项式
void negtive(); // 求反
void print();  // 遍历输出多项式
};
Poly::Poly(){
int m;
cout << "请输入多项式所包含的项数\n";
cin >> m;
cout << "请按升幂顺序,输入含有" << m << "项的多项式的系数和指数" << endl;
if (m!=0)
{
float coef[100];
int expn[100];
for (int i = 0; i < m; i++)
{
cin >> coef[i] >> expn[i];
polyNode node(coef[i], expn[i]);
l.insert(l.end(),node);  // 插入每个数据项
}
}
}
Poly::~Poly()
{
l.clear();
}
void Poly::print()
{
list<polyNode>::iterator iter ;
for (iter= l.begin(); iter != l.end(); iter++)
{
if (iter == l.begin())
{
cout << "(" << (*iter).coef << ")*X^" << (*iter).expn;
continue;
}
cout << "+(" << (*iter).coef << ")*X^" << (*iter).expn;
}
cout << endl;
}
void Poly::Add(Poly another)
{
list<polyNode>::iterator iter_this=l.begin(); 
list<polyNode>::iterator iter_another = another.l.begin();
while ((iter_this!=l.end())&&(iter_another!=another.l.end())) // 当两个多项式都没执行到底
{
if ((*iter_another).expn <(*iter_this).expn) // 当B多项式的幂比A多项式小
{
polyNode temp((*iter_another).coef, (*iter_another).expn);  // 将B多项式的第一项的值保存在新的一项中
iter_this=l.insert(iter_this, temp);  // 将新的项插入A之前
iter_this++;  // 执行上一条insert后,iter_this指向插入元素,原来的迭代器失效,故重新使迭代器为A多项式的当前项


another.l.pop_front(); // 删除B多项式的第一项
iter_another = another.l.begin();  // 重新使迭代器为B多项式的当前项
}
else if ((*iter_another).expn >(*iter_this).expn) // 当B多项式的幂比A多项式大
{
iter_this++;
}
else if ((*iter_another).expn ==(*iter_this).expn) // 当B多项式的幂与A多项式相等
{
(*iter_this).coef += (*iter_another).coef;
iter_another++;
if ((*iter_this).coef == 0) // 同指数两项相机系数为0,则删除该项
{
iter_this = l.erase(iter_this);
}
}
}
if (iter_this == l.end())  // 当A多项式执行完毕
{
while (iter_another != another.l.end())  // 把B中剩余项全部插入A尾部
{
l.push_back(*iter_another);
iter_another++;
}
}


}
void Poly::negtive()  
{
for (list<polyNode>::iterator iter = l.begin(); iter != l.end(); iter++)
{
(*iter).coef = -((*iter).coef);
}
}
void Poly::Sub(Poly another)
{
another.negtive();
Add(another);
}


int main()
{
cout << "--------------------A多项式-----------------\n";
Poly pa;
cout << "Fa(X)=";
pa.print();
cout << "--------------------B多项式-----------------\n";
Poly pb;
cout << "Fb(X)=";
pb.print();

Poly t1=pa,t2=pa;   // t1 t2 分别用来保存pa,pb

t1.Add(pb);
cout << "A+B=";
t1.print();
cout << endl;
t2.Sub(pb);
cout << "A-B=";
t2.print();


return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37174526/article/details/78207879