#include<iostream>
using namespace std;
typedef struct LNode {
int coef;
int exp;
LNode* next;
}LNode;
class poly {
LNode* head;
public:
void create(int n);//创建n项的多项式
int comp(int a, int b);
void addpoly(poly& ha, poly hb);
void print();
};
void poly::create(int n) {
head = new LNode;
head->next = NULL;
LNode* p;
for (int i = 0; i < n; i++) {
p = new LNode;
cin >> p->coef >> p->exp;//升序输入
p->next = head->next;
head->next = p;
}
}
int poly::comp(int a, int b) {
if (a > b)return -1;
else if (a == b)return 0;
else return 1;
}
void poly::addpoly(poly& ha, poly hb) {
LNode* q = ha.head, * pa = ha.head->next, * pb = hb.head->next, * r;
while (pa && pb)
switch (comp(pa->exp, pb->exp)) {
case -1: q = pa; pa = pa->next;
break;
case 0: pa->coef += pb->coef;
if (pa->coef == 0) {
q->next = pa->next;
delete pa;
pa = q;
}
else q = pa;
pa = pa->next;
pb = pb->next;
break;
case 1: r = new LNode;
r->coef = pb->coef;
r->exp = pb->exp;
q->next = r;
r->next = pa;
q = r;
pb = pb->next;
break;
}
while (pb != NULL) {
r = new LNode;
r->coef = pb->coef;
r->exp = pb->exp;
q->next = r;
r->next = pa;
q = r;
pb = pb->next;
}
}
void poly::print() {
LNode* p = head->next;
while (p) {
cout << p->coef << ' ' << p->exp << ' ';
p = p->next;
}
cout << endl;
}
int main() {
poly ha, hb;
cout << "创建多项式 1:" << endl;
ha.create(1); //创建 ha
cout << "创建多项式 2:" << endl;
hb.create(2); // 创建 hb
ha.print();
hb.print();
ha.addpoly(ha, hb); // 多项式相加
cout << "多项式之和:" << endl;
ha.print(); // 输出运算后的多项式
return 0;
}
欢迎指正