用C++语言编写一个程序,分别采用顺序表和带头结点的单链表存储一元多项式,并实现两个多项式相加运算, 要求: (1)创建存储多项式的有序表(按无序输入)ha和hb; (2)求ha和 hb相加产生多项式hc. (3)输出多项式ha、 hb和 he;
时间: 2024-10-23 14:11:45 浏览: 31
在C++中,我们可以使用`std::vector`(对于顺序表)和自定义结构体(表示多项式的系数和指数)来实现顺序表存储多项式,同时使用单链表(通过`struct Node`表示节点)来实现带头结点的单链表存储多项式。以下是实现这个功能的一个简单示例:
首先,我们定义一个多项式的结构体:
```cpp
struct Term {
int coefficient;
int exponent;
};
struct Polynomial {
std::vector<Term> coefficients; // 序列表存储多项式的系数
};
```
接下来,用于顺序列表的函数:
```cpp
void insertTerm(Polynomial& poly, int coef, int exp) {
poly.coefficients.push_back({coef, exp});
}
// 添加多项式
void addPolynomial(Polynomial& a, const Polynomial& b) {
for (const auto& term : b.coefficients) {
if (a.coefficients.empty() || a.coefficients.back().exponent < term.exponent) {
a.coefficients.push_back(term);
} else {
a.coefficients.back().coefficient += term.coeficient;
}
}
}
```
然后,链表部分:
```cpp
struct ListNode {
Term term;
ListNode* next;
};
void insertListNode(ListNode*& head, int coef, int exp) {
ListNode* newNode = new ListNode{ {coef, exp}, nullptr };
if (!head) {
head = newNode;
} else {
ListNode* current = head;
while (current->next && current->term.exponent > exp) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
// 链表版本的addPolynomial
void addPolynomialChain(ListNode*& aHead, const ListNode* bHead) {
ListNode* currentA = aHead, *currentB = bHead;
while (currentB && (currentA == nullptr || currentA->term.exponent < currentB->term.exponent)) {
currentA->term.coefficient += currentB->term.coefficient;
currentB = currentB->next;
}
aHead = currentA;
}
```
最后,展示多项式结果的函数:
```cpp
void displayPolynomial(const Polynomial& poly) {
for (const auto& term : poly.coefficients) {
if (term.coefficient != 0) {
std::cout << term.coefficient << "x^" << term.exponent << " + ";
}
}
std::cout << "\n";
}
```
完整的主函数可以像这样:
```cpp
int main() {
Polynomial ha, hb;
// 读取输入并插入多项式到ha和hb
// 实现顺序表和链表的相加
Polynomial hc;
addPolynomial(ha, hb); // 顺序表相加
addPolynomialChain(aHead, bHead); // 链表相加
displayPolynomial(ha);
displayPolynomial(hb);
displayPolynomial(hc);
return 0;
}
```
阅读全文