302023511023 李光桂.zip
立即下载
资源介绍:
302023511023 李光桂.zip
#include
using namespace std;
struct Node {
int coefficient;
int exponent;
Node* next;
Node(int coeff, int exp) : coefficient(coeff), exponent(exp), next(nullptr) {}
};
class Polynomial {
private:
Node* head;
public:
Polynomial() : head(nullptr) {}
void insertTerm(int coefficient, int exponent)
{
Node* newNode = new Node(coefficient, exponent);
if (!head || head->exponent < exponent)
{
newNode->next = head;
head = newNode;
}
else
{
Node* now = head;
Node* p = nullptr;
while (now && now->exponent >= exponent)
{
if (now->exponent == exponent)
{
now->coefficient += coefficient;
delete newNode;
return;
}
p = now;
now = now->next;
}
newNode->next = now;
if (p)
{
p->next = newNode;
}
}
}
Polynomial operator+(const Polynomial& other) {
Polynomial result;
Node* p1 = head;
Node* p2 = other.head;
while (p1 || p2)
{
if (!p1)
{
result.insertTerm(p2->coefficient, p2->exponent);
p2 = p2->next;
}
else if (!p2)
{
result.insertTerm(p1->coefficient, p1->exponent);
p1 = p1->next;
}
else if (p1->exponent > p2->exponent)
{
result.insertTerm(p1->coefficient, p1->exponent);
p1 = p1->next;
}
else if (p1->exponent < p2->exponent)
{
result.insertTerm(p2->coefficient, p2->exponent);
p2 = p2->next;
}
else
{
result.insertTerm(p1->coefficient + p2->coefficient, p1->exponent);
p1 = p1->next;
p2 = p2->next;
}
}
return result;
}
void print() const
{
Node* now = head;
while (now)
{
cout << now->coefficient << "x^" << now->exponent;
if (now->next)
cout << " + ";
now = now->next;
}
cout << endl;
}
~Polynomial()
{
while (head)
{
Node* temp = head;
head = head->next;
delete temp;
}
}
};
int main()
{
Polynomial p1;
p1.insertTerm(4, 3);
p1.insertTerm(4, 2);
p1.insertTerm(3, 0);
Polynomial p2;
p2.insertTerm(3, 2);
p2.insertTerm(2, 0);
Polynomial sum = p1 + p2;
cout << "P1: ";
p1.print();
cout << "P2: ";
p2.print();
cout << "Sum: ";
sum.print();
return 0;
}