I am trying to figure out why my Remove method is returning a NullPointerException. I have tested it against numerous scenarios and it seems to be working fine for the most part, but when I tested it against my professors code, I get a NullPointerException:
Against my Driver (this is the output):
List: Hamadi, Salisu, Galo, Ballo,
4
Replacing Galo with Abdullahi
List: Hamadi, Salisu, Abdullahi, Ballo,
Removing Salisu from the list
List: Hamadi, Abdullahi, Ballo,
List: 65, 21, 42,
Removing 65 from the list
List: 21, 42,
List: 1, 3,
Removing 1 from the list
List: 3,
List: 25, 3,
All works well until I test the code for my remove method (see below for the method) against my mentors code:
/** Remove a node at the specified index and return its data element.
* @param index The index of the element to remove
* @return The data element removed
* @throws IndexOutOfBoundsException If index is outside the bounds of the list
*
*/
public E remove(int index)
{
// TODO: Implement this method
if (index < 0 || index >= size() || size() == 0) {
throw new IndexOutOfBoundsException("Nodes are not within the array");
}
int i = 0;
LLNode<E> currentNode = head.next;
while (i < size) {
if (i == index) {
System.out.println("Removing " + currentNode.data + " from the list");
currentNode.next.prev = currentNode.prev;
currentNode.prev.next = currentNode.next;
size--;
return currentNode.data;
}
currentNode = currentNode.next;
i++;
}
return null;
}
Currently, the way I have implemented the removal of a node is to have the node that is being removedfor it's next node to point to the previous node of the removed node and vice versa.
Any input would be greatly appreciated on what I can do to further improve my remove method to prevent (and circumvent) any possible NullExceptionErrors. Thanks!