class Polynomial { public: Polynomial() : head(nullptr) {} ~Polynomial() { Node* curr = head; while (curr) { Node* temp = curr->next; delete curr; curr = temp; } } void insert(int
时间: 2024-02-14 17:32:57 浏览: 64
interpolating-polynomial:提供拉格朗日插值多项式的 Node.js 包
coefficient, int exponent) {
Node* newNode = new Node(coefficient, exponent);
if (!head) {
head = newNode;
return;
}
Node* curr = head;
Node* prev = nullptr;
while (curr && curr->exponent > exponent) {
prev = curr;
curr = curr->next;
}
if (!curr) {
prev->next = newNode;
} else if (curr->exponent == exponent) {
curr->coefficient += coefficient;
delete newNode;
} else if (!prev) {
head = newNode;
newNode->next = curr;
} else {
prev->next = newNode;
newNode->next = curr;
}
}
private:
class Node {
public:
int coefficient;
int exponent;
Node* next;
Node(int c, int e) : coefficient(c), exponent(e), next(nullptr) {}
};
Node* head;
};
这段代码实现了一个多项式类,其中包含插入方法 insert,用于按照指定的指数将系数插入多项式中。具体实现是通过遍历链表,找到合适的位置插入新节点,如果指数已存在则将系数相加。多项式的数据结构是一个链表,每个节点包含系数和指数。
阅读全文