class Polynomial { public: Polynomial() : head(nullptr) {} ~Polynomial() { Node* curr = head; while (curr) { Node* temp = curr->next; delete curr; curr = temp; } } void insert(int coeff, int exp) { Node* curr = head; Node* prev = nullptr; while (curr && curr->exp > exp) { prev = curr; curr = curr->next; } if (curr && curr->exp == exp) { curr->coeff += coeff; if (curr->coeff == 0) { if (prev) { prev->next = curr->next; } else { head = curr->next; } delete curr; } } else { Node* newNode = new Node(coeff, exp); if (prev) { prev->next = newNode; } else { head = newNode; } newNode->next = curr; } } void print() const { Node* curr = head; while (curr) { std::cout << curr->coeff << "x^" << curr->exp << " "; curr = curr->next; } std::cout << std::endl; } Node* head; // 多项式头结点 };
时间: 2024-02-10 14:30:17 浏览: 79
这段代码实现了多项式类,其中包含插入方法 insert 和打印方法 print。与之前的代码不同的是,这里的 insert 方法实现了系数为 0 时删除节点的功能,而且使用了更加简洁的写法。具体实现是通过遍历链表,找到合适的位置插入新节点,如果指数已存在则将系数相加。如果相加后系数为 0,则删除该节点。多项式的数据结构是一个链表,每个节点包含系数和指数。头结点 head 是公有成员,可以在类外部访问。打印方法 print 用于打印多项式的内容。
相关问题
class Polynomial { public: Polynomial() : head(nullptr) {} ~Polynomial() { Node* curr = head; while (curr) { Node* temp = curr->next; delete curr; curr = temp; } } void insert(int
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,用于按照指定的指数将系数插入多项式中。具体实现是通过遍历链表,找到合适的位置插入新节点,如果指数已存在则将系数相加。多项式的数据结构是一个链表,每个节点包含系数和指数。
Polynomial subtract(const Polynomial& p1, const Polynomial& p2) { Node* curr1 = p1.head; Node* curr2 = p2.head; Polynomial result; while (curr1 && curr2) { if (curr1->exp > curr2->exp) { result.insert(curr1->coeff, curr1->exp); curr1 = curr1->next; } else
if (curr1->exp < curr2->exp) { result.insert(-curr2->coeff, curr2->exp); curr2 = curr2->next; } else { double tempCoeff = curr1->coeff - curr2->coeff; if (tempCoeff != 0) { result.insert(tempCoeff, curr1->exp); } curr1 = curr1->next; curr2 = curr2->next; } } while (curr1) { result.insert(curr1->coeff, curr1->exp); curr1 = curr1->next; } while (curr2) { result.insert(-curr2->coeff, curr2->exp); curr2 = curr2->next; } return result; }
以上是一个多项式相减的函数实现,你有什么问题吗?
阅读全文