一.实验目的
1.理解单链表的结构特性和基本操作算法
2.掌握利用单链表实现两个多项式相加算法
二.实验内容
1.创建两个一元多项式;
2.输出一元多项式;
3.实现两个一元多项式相加;
4.输出相加后的一元多项式。
三.代码
#include <iostream>
using namespace std;
struct PolyNode {
double coef;
int exp;
PolyNode* next;
PolyNode(double c, int e): coef(c), exp(e), next(NULL) {}
};
PolyNode* create_poly() {
PolyNode* head = new PolyNode(0, 0);
PolyNode* cur = head;
int n;
cout << "请输入多项式的项数:";
cin >> n;
cout << "请按照指数从大到小的顺序依次输入" << n << "项的系数和指数(使用空格分隔):" << endl;
for (int i = 0; i < n; i++) {
double coef;
int exp;
cin >> coef >> exp;
cur->next = new PolyNode(coef, exp);
cur = cur->next;
}
return head->next;
}
void print_poly(PolyNode* p) {
bool first = true;
while (p) {
if (p->coef != 0) {
if (!first && p->coef > 0) {
cout << "+";
}
cout << p->coef;
if (p->exp > 1) {
cout << "x^" << p->exp;
} else if (p->exp == 1) {
cout << "x";
}
first = false;
}
p = p->next;
}
}
PolyNode* add_poly(PolyNode* poly1, PolyNode* poly2) {
PolyNode* head = new PolyNode(0, 0);
PolyNode* cur = head;
PolyNode* p = poly1;
PolyNode* q = poly2;
while (p && q) {
if (p->exp == q->exp) {
double coef_sum = p->coef + q->coef;
if (coef_sum != 0) {
cur->next = new PolyNode(coef_sum, p->exp);
cur = cur->next;
}
p = p->next;
q = q->next;
} else if (p->exp > q->exp) {
cur->next = new PolyNode(p->coef, p->exp);
cur = cur->next;
p = p->next;
} else {
cur->next = new PolyNode(q->coef, q->exp);
cur = cur->next;
q = q->next;
}
}
cur->next = p ? p : q;
return head->next;
}
int main() {
PolyNode* poly1 = create_poly();
cout << "多项式1:";
print_poly(poly1);
cout << endl;
PolyNode* poly2 = create_poly();
cout << "多项式2:";
print_poly(poly2);
cout << endl;
PolyNode* res = add_poly(poly1, poly2);
cout << "多项式1 + 多项式2:";
print_poly(res);
cout << endl;
return 0;
}