多项式相加
示例:
两个多项式相加:
5x^3 + 6x^4 + 4x^5
2x^2 + 5x^3 + 6x^6
结果:
2x^2 + 7x^4 + 4x^5 + 6x^6
先上运行结果:
源代码如下
#include<iostream>
using namespace std;
class Node {
public:
int coef;
int exp;
Node* next;
Node(int c, int e, Node* n = NULL) :coef(c), exp(e), next(n) {}
};
class Poly {
public:
Poly() :phead(NULL) {}
~Poly() {while (phead != NULL) { Node* temp = phead; phead = phead->next; delete temp; } }
Node* gethead() { return phead; }
void creat(int n); //创建一个多项式
void add(Node * p); //多项式相加
void print(); //将多项式在屏幕上显示出来
private:
Node* phead;
void append(int coef, int exp); //在多项式中添加一个项式
void add(int coef, int exp); //在多项式中加(一个)系数为coef指数为exp 的项式
};
void Poly::append(int coef, int exp) {
if (phead == NULL) { phead = new Node(coef, exp); return; }
Node* p = phead;
while (p->next != NULL) p = p->next;
p->next = new Node(coef, exp);
}
void Poly::creat(int n) {
int coef, exp;
for (int i = 0; i < n; i++) {
cout << "请输入" << i + 1 << "个项的系数与指数:" << endl;
cin >> coef >> exp;
append(coef, exp);
}
} //此函数将创建一个多项式
void Poly::add(int coef, int exp) {
if (phead == NULL) { phead = new Node(coef, exp); return; }
if (exp < phead->exp) { phead = new Node(coef, exp, phead); return; }
if (exp == phead->exp) {
phead->coef = phead->coef + coef;
if (phead->coef == 10) {
phead->coef = 1;
phead->exp++;
if (phead->exp == phead->next->exp) {
Node* temp = phead->next;
phead->next = temp->next;
add(temp->coef, temp->exp);
delete temp;
}
}
if (phead->coef > 10) {
phead->coef = phead->coef - 10;
add(1, phead->exp + 1);
}
}
else {
Node* p = phead;
while (p->next->exp < exp) {
p = p->next;
if (p->next == NULL) { append(coef, exp); return; }
}
if (p->next->exp == exp) {
p = p->next;
p->coef = p->coef + coef;
if (p->coef == 10) {
p->coef = 1;
p->exp++;
if (p->exp == p->next->exp) {
Node* temp = p->next;
p->next = temp->next;
add(temp->coef, temp->exp);
delete temp;
}
}
if (p->coef > 10) {
p->coef = p->coef - 10;
add(1, p->exp + 1);
}
}
else {
Node* temp = new Node(coef, exp, p->next);
p->next = temp;
}
}
}
void Poly::add(Node* p){
while (p != NULL) {
add(p->coef, p->exp);
p = p->next;
}
} //此函数将两个多项式相加
void Poly::print() {
Node* p = phead;
while (p != NULL) {
cout << p->coef << '^' << p->exp;
p = p->next;
if (p != NULL) cout << " + ";
}
cout << endl;
} //此函数将多项式在屏幕上显示
int main() {
Poly poly1, poly2;
int n1, n2;
cout << "请输入第一个多项式的项数:" << endl;
cin >> n1;
poly1.creat(n1);
cout << "第一个多项式如下:" << endl;
poly1.print();
cout << "请输入第二个多项式的项数:" << endl;
cin >> n2;
poly2.creat(n2);
cout << "第二个多项式如下:" << endl;
poly2.print();
poly1.add(poly2.gethead());
cout << "两个多项式相加的结果如下:" << endl;
poly1.print();
}