编写一个程序exp2-9.cpp,用单链表存储一元多项式,并实现两个多项式的相加运算
时间: 2024-12-28 10:41:02 浏览: 23
在C++中,我们可以编写一个名为`exp2-9.cpp`的程序,使用结构体和单链表来表示一元多项式,并实现两个多项式的相加操作。首先,我们需要创建一个包含系数和指数的节点结构体:
```cpp
// 定义多项式的节点结构
struct Term {
double coefficient; // 系数
int exponent; // 指数
Term(double coeff = 0, int exp = 0) : coefficient(coeff), exponent(exp) {}
};
// 定义多项式链表节点
struct PolynomialNode {
Term term;
PolynomialNode* next; // 指向下一个节点的指针
};
```
接下来,我们可以定义一个多项式类,包括添加新项、初始化以及相加功能:
```cpp
class Polynomial {
private:
PolynomialNode* head;
public:
Polynomial() : head(nullptr) {}
// 添加新的项到多项式
void addTerm(Term new_term) {
if (!head) {
head = new PolynomialNode{new_term, nullptr};
} else {
PolynomialNode* current = head;
while (current->next) {
current = current->next;
}
current->next = new PolynomialNode{new_term, nullptr};
}
}
// 相加两个多项式
void add(Polynomial& other) {
PolynomialNode* current1 = head;
PolynomialNode* current2 = other.head;
PolynomialNode* new_head = nullptr;
while (current1 && current2) {
double sum_coefficient = current1->term.coefficient + current2->term.coefficient;
int sum_exponent = std::max(current1->term.exponent, current2->term.exponent);
new_head = new PolynomialNode{sum_coefficient, sum_exponent, new_head};
if (current1->next)
current1 = current1->next;
if (current2->next)
current2 = current2->next;
}
if (current1) {
while (current1) {
new_head = new PolynomialNode{current1->term.coefficient, current1->term.exponent, new_head};
current1 = current1->next;
}
} else if (current2) {
while (current2) {
new_head = new PolynomialNode{current2->term.coefficient, current2->term.exponent, new_head};
current2 = current2->next;
}
}
head = new_head;
}
// 打印多项式
void print() {
PolynomialNode* current = head;
while (current) {
std::cout << current->term.coefficient << "x^" << current->term.exponent << " ";
current = current->next;
}
std::cout << "\n";
}
};
```
现在,你可以用这个类来创建两个多项式实例,然后相加它们:
```cpp
int main() {
Polynomial poly1;
poly1.addTerm({2.0, 1}); // 2x
poly1.addTerm({1.5, 2}); // 1.5x^2
poly1.print();
Polynomial poly2;
poly2.addTerm({3.0, 1}); // 3x
poly2.addTerm({4.0, 3}); // 4x^3
poly2.print();
Polynomial polySum;
polySum.add(poly1);
polySum.add(poly2);
polySum.print();
return 0;
}
```
运行此程序会得到两个多项式的和。
阅读全文