I am writing a program to implement a linked list. The list contains nodes that are used to represent terms in a polynomial function. I have a class called Polynomial
where I instantiate the linked list. The class has methods that allow you to modify the polynomial, including an addTerm method.
In my main, I would like to do something like this:
Polynomial p, q;
p.addTerm({ 4, 8 });
p.addTerm({ -3, 2 });
q = p;
p.addTerm({ 5, 6 });
p.addTerm({ 3, 2 });
this is the full Polynomial class:
class Polynomial {
Node* Head;
public:
Polynomial();
~Polynomial();
void addTerm(Term term);
unsigned int degree() const;
double coefficientFor(unsigned int exponent) const;
void clear();
private:
void DeleteInvalidNode();
};
and the constuctor:
Polynomial::Polynomial()
{
Head = 0;
}
For some reason, though, when I add the terms to p
after copying p
to q
it adds those terms to q
. From what I understand this is because when you copy an object to another object they point to the same thing. Is there any way that I can fix this to where when I modify p
it doesnt effect q
EDIT: I have now made an operator copy assignment function to try and copy the linked list.
I have written the following:
Polynomial& Polynomial::operator=(const Polynomial& rhs)
{
Node* Temp = rhs.Head;
while (rhs.Head != NULL)
{
Temp = rhs.Head->next;
this->addTerm({ rhs.coefficientFor(degree()), rhs.degree() });
rhs.Head = Temp;
}
return *this;
}
It is not working though since rhs is constant and I am trying to modify it. I am very new to linked lists. How would I go about fixing this to where it can work?