已知一元多项式:A(x)=a0+a1x+a2x2+a3x3+….anxn, B(x)= b0+b1x+b2x2+b3x3+….bmxm设计算法实现C(x)=A(x)+B(x)。功能包括输入多项式A,输入多项式B,求A和B的和,显示求和后的结果等操作。本题中,链表的第一个元素位置为1,链表的数据域格式为 : coef exp 其中coef为系数,exp为指数。 #include using namespace std; struct Node{ int coef,exp; Node *next; };
class Polynomial { public: Polynomial(); void Print(); void InputA(); void InputB(); void Add_AB(); private: Node *first1; Node *first2; };
Polynomial::Polynomial(){ first1 = new Node; first1->next = NULL; first2 = new Node; first2->next = NULL; }
void Polynomial::InputA(){ Node *r = NULL,*s = NULL; r = first1; int coef, exp; while (1) { cin >> coef >> exp; if(coef != 0) { s = new Node; s->coef = coef; s->exp = exp; s->next = r->next; r->next = s; r = s; } else{ break; } } }
void Polynomial::InputB() { Node *r = NULL,*s = NULL; r = first2; int coef, exp; while (1) { cin >> coef >> exp; if(coef != 0) { s = new Node; s->coef = coef; s->exp = exp; s->next = r->next; r->next = s; r = s; } else{ break; } } }
void Polynomial::Add_AB() { Node *pre = first1,*p = pre->next; Node *qre = first2,*q = qre->next; Node *qtemp = NULL; while (p != NULL && q != NULL) { if (p->exp < q->exp) { pre = p; p = p->next; } else if(p->exp > q->exp) { qtemp = q->next; pre->next = q; q->next = p; pre = pre->next; q = qtemp; } else { p->coef = p->coef + q->coef; if (p->coef == 0) { pre->next = p->next; delete p; p = pre->next; } else { pre = p; p = p->next; } qre->next = q->next; delete q; q = qre->next; } } if (q != NULL) { pre->next = q; } p = first1->next; while (p != NULL) { cout << p->coef << " " << p->exp << endl; p = p->next; }
} int main() { Polynomial p; char t; while(1) { cin >> t; if(t == ‘A’) { p.InputA(); } else if(t == ‘B’) { p.InputB(); } else if (t == ‘C’) { p.Add_AB(); } else { break; } } }