0

hi my remove node is not working....can someone help me correct it

```
// Polynomial.java
public class Polynomial
{
private int degree;
private Node head;
public static Polynomial addPolys(Polynomial poly1, Polynomial poly2)
{
Polynomial polyRes = new Polynomial();
int power = (poly1.degree > poly2.degree) ? poly1.degree : poly2.degree;
while (power >= 0)
{
Node n1 = poly1.head;
while (n1 != null)
{
if (n1.power == power)
break;
n1 = n1.next;
}
Node n2 = poly2.head;
while (n2 != null)
{
if (n2.power == power)
break;
n2 = n2.next;
}
if ((n1 != null) && (n2 != null))
polyRes.addNode(n1.coeff + n2.coeff, n1.power);
else if (n1 != null)
polyRes.addNode(n1.coeff, n1.power);
else if (n2 != null)
polyRes.addNode(n2.coeff, n2.power);
power--;
}
return polyRes;
}
public void addNode(int coeff, int power)
{
if (head == null) // start the list
{
head = new Node(coeff, power, null);
degree = power;
}
else
{
Node n = head;
Node last = null;
while (n != null)
{
if (power > n.power) // insert in list
{
if (last == null)
head = new Node(coeff, power, n);
else
last.next = new Node(coeff, power, n);
degree = power;
break;
}
last = n;
n = n.next;
}
if (n == null) // append to list
{
last.next = new Node(coeff, power, null);
}
}
}
//loop though the nodes until we got to the desired index - 1 and keep the reference of the node as A (A is the node right before the node we want to remove)
public void removeNode(int indexnumber)
{
Node n = head;
int i = 0;
while (i < indexnumber - 1){
n = n.next;
if(n.next == null)
//throw exception
++i;
}
Node A = n;
//(if we encounter a node with the next node pointing to null, thow an exception)
Node B = A.next; //B is the node we want to remove
Node C = B.next; //C is the node right after the node we want to remove
A.next = C;
B.next = null;
}
public String toString()
{
StringBuffer strBuf = new StringBuffer();
Node n = head;
boolean first = true;
while (n != null)
{
int absCoef = n.coeff;
if (!first)
{
if (n.coeff >= 0)
strBuf.append(" + ");
else
{
absCoef = -absCoef;
strBuf.append(" - ");
}
}
strBuf.append(absCoef).append("x^^").append(n.power);
first = false;
n = n.next;
}
return strBuf.toString();
}
public class Node
{
public int coeff;
public int power;
public Node next;
public Node(int coeff, int power, Node next)
{
this.coeff = coeff;
this.power = power;
this.next = next;
}
}
}
```

*Edited 3 Years Ago by happygeek*: fixed formatting