用cpp语言设计一个多项式相加的程序,要求写出完整的代码,对多项式进行的第一个操作是对数据项中的变量排序,输入多项式之后,每个数据项都分别用排序向量进行排序,链表中的节点可以对该向量进行访问.第二个操作是多项式相加.这个过程是由创建一个链表开始的,这个链表是由待相加的多项式的节点副本组成的.通过这种方式,两个多项式都不会受到影响,并且可以在其他操作中使用.
时间: 2023-01-11 17:55:36 浏览: 131
两个多项式相加.cpp
以下是用 C++ 实现多项式相加的代码示例:
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <unordered_map>
using namespace std;
struct Node {
vector<int> coeffs;
int degree;
Node *next;
Node(vector<int> coeffs, int degree) : coeffs(coeffs), degree(degree), next(nullptr) {}
};
// 根据指数从大到小排序
bool compare(const Node &n1, const Node &n2) {
return n1.degree > n2.degree;
}
// 将节点插入链表
void insert(Node *&head, Node *node) {
if (!head) {
head = node;
return;
}
if (head->degree < node->degree) {
node->next = head;
head = node;
return;
}
Node *curr = head;
while (curr->next && curr->next->degree >= node->degree) {
curr = curr->next;
}
node->next = curr->next;
curr->next = node;
}
// 将链表中的节点复制到另一个链表中
void copy(Node *&dst, Node *src) {
while (src) {
Node *node = new Node(src->coeffs, src->degree);
insert(dst, node);
src = src->next;
}
}
// 将两个多项式相加,返回相加后的多项式
Node *add(Node *poly1, Node *poly2) {
Node *result = nullptr;
Node *curr1 = poly1, *curr2 = poly2;
while (curr1 && curr2) {
if (curr1->degree == curr2->degree) {
// 将两个多项式的系数相加
vector<int> coeffs;
for (int i = 0; i < curr1->coeffs.size(); i++) {
coeffs.push_back(curr1->coeffs[i] + curr2->coeffs[i]);
}
Node *node = new Node(coeffs, curr1->degree);
insert(result, node);
curr1 = curr1->next;
curr2 = curr2->next;
} else if (curr1->degree > curr2->degree) {
insert(result, new Node(curr1->coeffs, curr1->degree));
curr1
阅读全文