资源描述:
《《数据结构a》第02章——03》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、数据结构DataStructuresinC++2.4多项式的算术运算多项式相加p(x)=3x14−8x8+6x2+2q(x)=2x10+4x8−6x2q(x)p(x)+q(x)结果:q(x)=3x14+2x10−4x8+2多项式的逻辑结构:视为线性表p(x)=3x14-8x8+6x2+2数据元素(coef,exp)表示多项式项coef·xexp,coef是该项的系数,exp是变元x的指数。多项式的存储表示p(x)=3x14-8x8+6x2+2((3,14),(-8,8),(6,2),(2,0))顺序表示线性表长度事先难以确定;算术运算需插入和删除元素。多项式的
2、链接表示多项式的项2.4.1项结点类项结点类Term*InsertAfter(intc,inte)构造一个新项(c,e)结点,插在*this项之后,函数返回新项结点的地址。classTerm{public:Term(intc,inte);//构造函数1Term(intc,inte,Term*nxt);//构造函数2Term*InsertAfter(intc,inte);private:intcoef;intexp;Term*link;friendostream&operator<<(ostream&,constTerm&);//重载“<<”,输出多项式的一项fr
3、iendclassPolynominal;};构造函数Term::Term(intc,inte):coef(c),exp(e){link=0;}Term::Term(intc,inte,Term*nxt):coef(c),exp(e){link=nxt;}Term::Term(intc,inte){coef=c;exp=e;link=0;}InsertAfter函数实现Term*Term::InsertAfter(intc,inte){link=newTerm(c,e,link);returnlink;}调用语句:q=q->InsertAfter(c,e);Te
4、rm::Term(intc,inte,Term*nxt):coef(c),exp(e){link=nxt;}重载输出运算符ostream&operator<<(ostream&out,constTerm&val){//用-4x^2表示-4x2。if(val.coef= =0)returnout;out<5、l{public:Polynominal();~Polynominal();voidAddTerms(istream&in);//建立多项式链表voidOutput(ostream&out)const;//输出多项式voidPolyAdd(Polynominal&r);//多项式相加…private:Term*theList;//单循环链表的表头指针friendostream&operator<<(ostream&,constPolynominal&);friendistream&operator>>(istream&,Polynominal&);friendP
6、olynominal&operator+(Polynominal&,Polynominal&);};2.4.4多项式类的实现构造函数Polynominal::Polynominal(){theList=newTerm(0,−1);theList->link=theList;}5.2.5多项式的输入和输出输入多项式voidPolynominal::AddTerms(istream&in){Term*q=theList;intc,e;for(;;){cout<<"Inputaterm(coef,exp):"<>c>>e;if(e<0)break
7、;q=q->InsertAfter(c,e);}}p(x)=3x14-8x8+6x2+2输出多项式voidPolynominal::Output(ostream&out)const{boolstart=true;Term*p=theList->link;out<<"Thepolynominalis:"<link){if(!start&&p->coef>0)out<<'+';start=false;out<<*p;}out<exp==q->exp,则同类项合并,令q->coe
8、f=q->coef+p-