#include <iostream> #include <list> #include <algorithm> using namespace std; typedef struct { float coef;//系数 int expn;//指数 }Element; class Polynomial { public: void create(); void display(); void add(Polynomial &poly, Polynomial &result); private: list<Element> mylist; }; void Polynomial::create() { int a, b; Element elemnet; cout<<"当输入的a为0时,表示输入结束!"<<endl; while ((cin>>a>>b) && (a != 0)) { elemnet.coef = a; elemnet.expn = b; mylist.push_back(elemnet); } } void Polynomial::display() { list<Element>::iterator iter = mylist.begin(); while(iter != mylist.end()) { cout<<(*iter).coef<<"-"<<(*iter).expn<<" "; ++iter; } cout<<endl; } void Polynomial::add(Polynomial &poly, Polynomial &result) { list<Element>::iterator iter1 = mylist.begin(), iter2 = mylist.end(); list<Element>::iterator iter3 = poly.mylist.begin(), iter4 = poly.mylist.end(); while ((iter1 != iter2) && (iter3 != iter4)) { if ((*iter1).expn < (*iter3).expn) { result.mylist.push_back(*iter1); ++iter1; } else if ((*iter1).expn > (*iter3).expn) { result.mylist.push_back(*iter3); ++iter3; } else { Element temp; temp.coef = (*iter1).coef + (*iter3).coef; temp.expn = (*iter1).expn; cout<<temp.coef<<endl; result.mylist.push_back(temp); ++iter1; ++iter3; } } while (iter1 != iter2) { result.mylist.push_back(*iter1++); } while (iter3 != iter4) { result.mylist.push_back(*iter3++); } } int main() { Polynomial p1, p2, result; p1.create(); p2.create(); p1.display(); p2.display(); p1.add(p2, result); result.display(); return 0; }