I have been trying to work on a linked list implementation I thought I had it nailed, but for some reason I can’t work out how to add a new node to the list at the start of the list.
This was a polynomial addition method, everything else works as expected, but this section does not work as expected. It returns polynomial with no changes… I think I am missing something really simple but cant see it.
else if (power > polynomial.powerMax())
{
Polynomial newlink = new Polynomial(coefficient,power);
newlink.successor = polynomial;
polynomial = newlink;
}
Whole Method
public class Polynomial
{
final static private int mantissa = 52;
final static private double epsilon = Math.pow(2.0, -mantissa);
private double coefficient = 0.0;
private int power = 0;
private Polynomial successor=null;
public Polynomial(double coefficient, int power)
{
if (Double.isNaN(coefficient)) return;
if (Math.abs(coefficient) < epsilon) return;
if (power<0) return;
this.coefficient=coefficient;
this.power=power;
}
public static void add(Polynomial polynomial, double coefficient, int power)
{
if (polynomial == null) return;
if (Math.abs(coefficient) < epsilon) coefficient = 0.0;
if (coefficient == 0.0) return;
if (power < 0) return;
if (power < polynomial.powerMin())
{
Polynomial newNode = new Polynomial(coefficient,power);
if (polynomial.successor != null)
{
while (polynomial.successor != null)
{
polynomial.successor = polynomial.successor.successor;
}
polynomial.successor = newNode;
}
else if (polynomial.successor == null )
polynomial.successor = newNode;
}
else if (power > polynomial.powerMax())
{
Polynomial newlink = new Polynomial(coefficient,power);
newlink.successor = polynomial;
polynomial = newlink;
}
else
{
if (power == polynomial.power)
polynomial.coefficient = polynomial.coefficient + coefficient;
}
}
In Java the references of variables are passed by value (link). That means if you assign anything new to the variable polynomial it will not have any effect outside of this method.
Will print
You need to return the new Polynomial you created from the add method.