程序代码:
#include <iostream> using namespace std; class Term { private: int coef; int exp; Term *link; friend ostream & operator << (ostream & ,const Term &); friend class Polynominal; public: Term(int c,int e):coef(c),exp(e) { link=0; } Term(int c,int e,Term* nxt):coef(c),exp(e) { link=nxt; } Term* InsertAfter(int c,int e) { 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 { private: Term* thelist; int n; friend ostream & operator <<(ostream&, const Polynominal &); friend istream & operator >>(istream&,Polynominal &); friend Polynominal & operator +(Polynominal &, Polynominal &); friend Polynominal & operator * (Polynominal &a ,Polynominal &b); public: Polynominal() { thelist=new Term(0,-1); thelist->link=thelist; n=0; } // 合并次数相同的项, 只需在加法中调用 void simplify() { Term* target, *iter, *post_iter; target = thelist->link; while(target->exp != -1) { post_iter = target; iter = target->link; while(iter->exp != -1) { if(iter->exp == target->exp) { target->coef += iter->coef; post_iter->link = iter->link; delete iter; iter = post_iter->link; } else { iter = iter->link; post_iter = post_iter->link; } } target = target->link; } } void AddTerms(istream& in) { Term* q=thelist; int c,e; for(;;) { cout<<"Input a term(coef,exp):\n"; cin>>c>>e; if(e<0) break; q=q->InsertAfter(c,e); n++; } } void Output(ostream& out) const { int first=1; Term *p=thelist->link; cout<<"The Polynominal is :\n"; for(;p!=thelist; p=p->link) { if(!first&&(p->coef>0)) out<<"+"; first=0; out<<*p; } cout<<endl; } void PolyAdd(Polynominal& r) { Term *q,*q1=thelist,*p; p=r.thelist->link; q=q1->link; while(p->exp>=0) { while(p->exp< q->exp) { q1=q;q=q->link; } if(p->exp==q->exp) { q->coef=q->coef+p->coef; if(q->coef==0) { q1->link=q->link;delete q; q=q1->link; } else { q1=q;q=q->link; } } else { n++; q1=q1->InsertAfter(p->coef,p->exp); } p=p->link; } //======================================================= simplify(); //======================================================= } }; 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; } int main() { Polynominal p,q; cin>>p; cout<<p; cin>>q; cout<<q; q+p; cout<<q; }
If You Want Something, Go Get It, Period.