使用链表实现多项式求值完整代码
时间: 2023-08-15 12:15:34 浏览: 240
```
#include <iostream>
#include <cmath>
using namespace std;
struct Node {
double coef; // 系数
int expn; // 指数
Node *next; // 指向下一个节点的指针
};
int main() {
Node *head = new Node(); // 创建一个头结点,不存储任何项
head->next = nullptr;
int n; // 多项式项数
cout << "请输入多项式的项数:";
cin >> n;
cout << "请输入多项式的每一项(系数 指数):" << endl;
for (int i = 0; i < n; i++) {
double coef;
int expn;
cin >> coef >> expn;
Node *p = head;
while (p->next != nullptr && p->next->expn < expn) {
p = p->next;
}
if (p->next != nullptr && p->next->expn == expn) {
p->next->coef += coef; // 如果指数相同,则合并同类项
} else {
Node *q = new Node();
q->coef = coef;
q->expn = expn;
q->next = p->next;
p->next = q;
}
}
double x;
cout << "请输入 x 的值:";
cin >> x;
double result = 0;
Node *p = head->next;
while (p != nullptr) {
result += p->coef * pow(x, p->expn);
p = p->next;
}
cout << "多项式的值为:" << result << endl;
// 释放链表占用的内存
p = head;
while (p != nullptr) {
Node *q = p;
p = p->next;
delete q;
}
return 0;
}
```
阅读全文