c++中 用链式表实现两个多项式的输入,显示,相加和的显示 程序怎么写
时间: 2024-10-10 08:10:04 浏览: 25
基于C++的一元多项式相加.zip
在C++中,你可以通过定义结构体表示多项式项,然后使用链表数据结构存储每个多项式的系数和次数。这里是一个简单的示例程序,展示了如何实现两个多项式的输入、相加以及结果的显示:
```cpp
#include <iostream>
using namespace std;
// 定义多项式的项
struct Term {
int coef; // 系数
int exp; // 次数
// 构造函数
Term(int c = 0, int e = 0) : coef(c), exp(e) {}
};
// 链表节点用于存储多项式的项
struct PolynomialTerm {
Term term;
PolynomialTerm* next; // 指向下一个项
};
// 多项式类
class Polynomial {
private:
PolynomialTerm* head;
public:
void input() {
PolynomialTerm* current = new PolynomialTerm();
current->term.coef = 0;
current->term.exp = 0;
current->next = nullptr;
cout << "请输入多项式的项(格式:系数 次数,输入结束请输入0 0):" << endl;
while (true) {
cin >> current->term.coef >> current->term.exp;
if (current->term.coef == 0 && current->term.exp == 0)
break;
current->next = new PolynomialTerm();
current = current->next;
}
head = current;
}
void display() {
PolynomialTerm* temp = head;
while (temp != nullptr) {
cout << temp->term.coef << "x^" << temp->term.exp << " ";
temp = temp->next;
}
cout << "\n";
}
Polynomial add(Polynomial& other) {
Polynomial result;
PolynomialTerm* current1 = head;
PolynomialTerm* current2 = other.head;
PolynomialTerm* temp = new PolynomialTerm();
while (current1 != nullptr || current2 != nullptr) {
int sum_coef = current1 ? current1->term.coef : 0;
if (current2 != nullptr)
sum_coef += current2->term.coef;
temp->term.coef = sum_coef;
temp->term.exp = max(current1->term.exp, current2->term.exp);
result.insertAfter(temp);
current1 = current1 ? current1->next : nullptr;
current2 = current2 ? current2->next : nullptr;
}
return result;
}
void insertAfter(Term& term) {
if (head == nullptr) {
head = new PolynomialTerm(term);
return;
}
PolynomialTerm* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = new PolynomialTerm(term);
}
// 显示添加后的结果
void displayResult() {
display();
}
};
int main() {
Polynomial p1, p2;
p1.input();
p2.input();
Polynomial result = p1.add(p2);
result.displayResult();
return 0;
}
```
这个程序首先定义了`Term`和`PolynomialTerm`结构,接着在`Polynomial`类中实现了输入、显示、相加以及插入项的功能。在`main`函数中创建两个`Polynomial`对象,并执行操作。
阅读全文