Search code examples
javalinked-listpolynomialsderivativeexponent

Polynomial Derivative handling exponent of 0


I have a method that takes in a polynomial Linked List as a parameter and returns a new list, which is the derivative of the polynomial.

Here's what I have:

private PolyNode derivative(PolyNode poly) {
    PolyNode temp = new PolyNode(0, 0);
    PolyNode res = temp;

    // While both Lists are not empty
    while (poly != null) {
        if (poly.power > 0) {
            temp.next = new PolyNode(poly.coef * poly.power, poly.power - 1);
            temp = temp.next;
            poly = poly.next;
        }
    }
    // Return new List, the result polynomial
    return res.next;
}

When I run the program, it never finishes compiling and partially returns the list; only the terms that have a higher power than 0. I tried adding

if (poly.power == 0) {
    temp.next = new PolyNode(0,0);
    temp = temp.next;
    poly = poly.next;
}

But that doesn't seem to work. Any thoughts?


Solution

  • Look closely to your while loop:

    // While both Lists are not empty
    while (poly != null) {
        if (poly.power > 0) {
            temp.next = new PolyNode(poly.coef * poly.power, poly.power - 1);
            temp = temp.next;
            poly = poly.next;
        }
    }
    

    poly won't change unless its power is greater than zero. So when a poly with 0 power is found, your loop gets stuck.

    Change it to:

    while (poly != null) {
        if (poly.power > 0) {
            temp.next = new PolyNode(poly.coef * poly.power, poly.power - 1);
            temp = temp.next;
        }
        poly = poly.next;
    }
    

    This way you effectively throw out any constant (power == 0), while still looping over poly list.