ifndef POLY_H
#define POLY_H

class Poly {

public:

    Poly() : first(0) { }
        
    void addTerm(double coeff, unsigned exponent);
        // add term (coeff^exponent) to the polynomial;
        // might just change coefficient of existing term,
        // or might insert new term; maintains terms
        // in order from greatest to least exponent


private:

    struct Term {
        double coeff;
        unsigned exponent;
        Term *next;

        Term(double c=0, unsigned e=0) // Term constructor done
            : coeff(c), exponent(e), next(0) { }
    };

    Term *first; // pointer to first polynomial term

    void printAbsTerm(Term *t) const;
        };

#endif

I need some help so I can understand what I need to do. How can I go about starting to add a term with coefficient and exponent?

Before one adds a term, one must find out whether said term exists. If so, replace. If not, add. So first iterate through all the terms and look for the exponent. If it exists, that's the easy case. Replace the coefficient and you're done.

If not, add the term. First, are these terms ordered in any way(i.e. the exponent)? If so, you'll want to place the new term in the appropriate place. If not, stick it at the end or at the beginning. I would order the terms by exponent, high to low. It makes the math and searching easier and it's how we are used to seeing and thinking of them anyway. Insertion is just like with any linked list. Create the new term, then adjust the next pointers.

Maybe an example would help :

Suppose this is your current polynomial : [tex] 4x^3 + 2x^2 + x + 3 [/tex]
and you want to add the term [tex] 5x^2 [/tex].

Then you look at you list of terms, and see if there is a term with an exponent equal to 2, and looking at it we see that there is a term with its coefficient equal to 2, that is this term [tex]2x^2[/tex]. So we just add it, [tex]2x^2 + 5x^2[/tex] = [tex] 7x^2[/tex], and so your new polynomial will be [tex] 4x^3 + 7x^2 + x + 3 [/tex]

Now what happens if we want to add [tex] 2x^6[/tex] ? What should u do?

Edited 5 Years Ago by firstPerson: n/a

so, I should firts loop through my given polynomial.
Then check if the term im adding has the same exponent as a term already in the polynomial, if it does, I should add them together and put it in the right place.
If I want to add a term with a higher exponent, I just set it as the first term.... correct?

If there is a match, then all you have to do is add the coefficients, else if there is not a match, then
you will needed to create a slot for the new term. Now where should the slot go? You need to make sure that the list is in order though.

This article has been dead for over six months. Start a new discussion instead.