#include <iostream>
#include <string>
using namespace std;
class Term
{
public:
Term(int c, int e);
Term(int c, int e, Term* nxt);
Term* InsertAfter(int c, int e);//在this指针指示的结点后抓人新结点
int coef;
int exp;
Term* link;
private:
friend ostream& operator<<(ostream&, const Term&);
friend class Ploynominal;
};
Term::Term(int c, int e) :coef(c), exp(e)
{
link = 0;
}
Term::Term(int c, int e, Term* nxt) :coef(c), exp(e)
{
link =nxt;
}
Term* Term::InsertAfter(int c, int e)
{
//为新项申请结点的存储单元,并用Term函数将c,e和this->link的值填入新节点的相应域
link = new Term(c,e,link);
return link;
}
ostream& operator<<(ostream& out, const Term& val)
{
if (val.coef == 0) return out;
out << val.coef;
switch (val.exp)
{
case 0:break;
case 1:out << "X"; break;
default:out << "X^" << val.exp;break;
}
return out;
}
class Polynominal
{
public:
Polynominal();
~Polynominal();
void AddTerms(istream& in);//输人多项式的各项,构造多项式链表
void Output(ostream& out) const;//将多项式送输出流
void PolyAdd(Polynominal& r);//多项式相加
private:
Term* theList;//单循环链表的表头指针
friend ostream& operator << (ostream&, const Polynominal&);
friend istream& operator >>(istream&, Polynominal&);
friend Polynominal& operator +(Polynominal&, Polynominal&);
};
Polynominal::Polynominal()
{
//创建多项式的空的单循环链表
theList = new Term(0, -1);
theList->link = theList;//分配表头结点的存储单元,构成循环链表
}
Polynominal::~Polynominal()
{
//撒销多项式的单循环链表
Term* p = theList->link;
while (p != theList)
{
theList->link = p->link;//删除p结点
delete p;//释放p之存储空间
p = theList->link;//p指向下1个待删除结点
}
delete theList;//释放表头结点的存储单元
}
void Polynominal::AddTerms(istream& in)
{
//按降事输人各项,构造单循环链表、
Term* q = theList;
int c, e;
for (;;)
{
cout << "Input a term(coef.exp):\n" << endl;
cin >> c >> e;
if (e < 0) break;//当输人的指数小于0时,构造过程结束
q = q->InsertAfter(c, e);//将c,e插人表尾结点q之后
}
}
void Polynominal::Output(ostream& out) const
{
int first = 1; Term* p = theList->link;
cout << "The polynomina1 is: \n" << endl;
for (; p != theList; p = p->link)
{
if (!first && (p->coef > 0)) out << "+"; //在非第一 项的正系数前输出+号
first = 0;
out << *p;//调用Term类上重载的"<<"操作
}
cout << "\n" << endl;
}
void Polynominal::PolyAdd(Polynominal& r)
{
Term* q, * ql = theList, * p;
p = r.theList->link;
q = ql->link;
while (p->exp >= 0)
{
//对r的单循环链表遍历,直到到全部结点都处理完
while (p->exp < q->exp)
{
//跳过q->exp大的项
ql = q;
q = q->link;
}
if (p->exp == q->exp)
{
//当指数相等时,系数相加
q->coef = q->coef + p->coef;
if (q->coef == 0)
{
//若相加后系数为0.则删除q
ql->link = q->link;
delete(q);
q = ql->link;//重置q指针
}
else
{
ql = q;
q = q->link;//若相加后系数不为0,则移动q1和q
}
}
else
ql = ql->InsertAfter(p->coef, p->exp); //以 P的系数和指数生成新结点,插人q1后
p = p->link;
}
}
ostream& operator << (ostream& out, const Polynominal& x)
{
x.Output(out);
return out;
}
istream& operator >>(istream& in, Polynominal& x)
{
x.AddTerms(in);
return in;
}
Polynominal& operator +(Polynominal &a,Polynominal& b)
{
a.PolyAdd(b);
return a;
}
void main()
{
Polynominal p, q;
cin >> p; cout << p;
cin >> q; cout << q;
q = q + p; cout << q;
}
利用线性表实现多项式的算术运算
最新推荐文章于 2023-05-01 20:57:54 发布