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; // 多项式头结点 }; Polynomial add(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 { int sum = curr1->coeff + curr2->coeff; result.insert(sum, curr1->exp); curr1 = curr1->next; curr2 = curr2->next; } } while (curr1) { result.insert(curr1->coeff, curr1->exp); curr1 = curr1->next; } while (curr2) { result.
时间: 2024-02-14 21:14:35 浏览: 88
在这段代码中,定义了一个多项式类 Polynomial,其中包含一个链表结构,每个节点表示多项式的一个单项式,具有系数和指数两个成员变量。类中包含了一个插入单项式的方法 insert,一个打印多项式的方法 print,还有一个多项式相加的全局函数 add。在 add 函数中,使用了两个指针 curr1 和 curr2 分别指向两个多项式的头结点,通过比较指数的大小,向结果多项式中依次插入单项式,如果指数相同则将系数相加。最后将指针剩下的单项式插入到结果多项式中。
阅读全文