I have a linked list that is represented as
struct term{
double coef;
unsigned deg;
struct term * next;
};
then i have a polynomial class
class Polynomial{
public:
Polynomial & operator+ (const Polynomial & ) const;
private:
term *ptr
and i am trying to do an addition overloaded operator, but what i tried just give me some random part of the polynomial that is in the middle.
Polynomial & Polynomial::operator+(const Polynomial & poly) const{
Polynomial p2 = *this;
term * temp = (*this).ptr;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = poly.ptr;
return p2;
}
and also when i have 2 polynomials, one is a copy of another just then added one more term, then when i try to use the addition operator, the first polynomial is bigger, like the second polynomial is added to it.
You’re operator+() is seriously whacked. Consider the idea of “term” ownership. Each polynomial has a linked list of terms. It owns this list (at least it better). Now consider this brief analysis of your
operator +():I sincerely hope it is evident what is wrong with that. For this to work correctly, your operator should be returning a by-val, (which it is, hooray!), and manufacture that thing correctly:
p2) of *this (you have that)p2rhsparameter ofoperator +(const Polynomial* rhs), linking the copies one-by-one to the tail ofp2‘s term list. Note: the tail will move with each new term linked.rhsshould be untouched.Thats about the extent I can offer. Good luck.
PS: For extra-credit-bonus-round, sort your terms in your list as you insert them. This will get you one step closer to a like-degree merge, which will be the backbone of
operator +=()and greatly assist youroperator +(). The latter literally degenerates toPolynomial p2 = *this; p2 += poly; return p2;