C++内容:编写一个程序,用单链表存储一元多项式,并实现两个多项式相加的运算。
时间: 2024-09-23 17:00:58 浏览: 93
在C++中,你可以使用结构体或类来表示一元多项式的项,然后通过单链表的数据结构来存储多项式的各个系数和指数。下面是一个简单的示例,展示如何创建链表节点、多项式结构以及相加操作:
```cpp
#include <iostream>
using namespace std;
// 定义链表节点结构,包含系数和指数
struct Term {
int coefficient;
int exponent;
Term* next; // 指向下一个节点的指针
};
// 创建多项式类
class Polynomial {
private:
Term* head; // 链表头节点
public:
Polynomial() : head(nullptr) {}
// 添加项到多项式
void addTerm(int c, int e) {
Term* newNode = new Term();
newNode->coefficient = c;
newNode->exponent = e;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
} else {
Term* current = head;
while (current->next != nullptr && current->exponent < e) {
current = current->next;
}
current->next = newNode;
}
}
// 相加两个多项式
friend Polynomial operator+(const Polynomial& poly1, const Polynomial& poly2);
};
// 实现两个多项式的相加运算符重载
Polynomial operator+(const Polynomial& poly1, const Polynomial& poly2) {
Polynomial result;
Term* current1 = poly1.head;
Term* current2 = poly2.head;
// 合并项
while (current1 != nullptr || current2 != nullptr) {
int sumCoefficient = 0;
if (current1 != nullptr) {
sumCoefficient += current1->coefficient;
current1 = current1->next;
}
if (current2 != nullptr && (current1 == nullptr || current2->exponent > current1->exponent)) {
sumCoefficient += current2->coefficient;
current2 = current2->next;
}
result.addTerm(sumCoefficient, current1 == nullptr ? current2->exponent : current1->exponent);
}
return result;
}
int main() {
Polynomial p1, p2;
p1.addTerm(2, 1); // 2x^1
p1.addTerm(3, 2); // 3x^2
p2.addTerm(4, 1); // 4x^1
p2.addTerm(-1, 3); // -1x^3
Polynomial sum = p1 + p2; // 相加
for (Term* term = sum.head; term != nullptr; term = term->next) {
cout << term->coefficient << "x^" << term->exponent << " ";
}
cout << endl;
return 0;
}
```
这个程序首先定义了`Term`结构体用于存储单个项,接着`Polynomial`类负责存储链表和提供添加项的方法。最后,我们实现了`+`运算符重载,使得可以方便地对两个多项式进行相加。
阅读全文