Linuxn00b Linuxn00b - 1 year ago 73
Java Question

Remove method in LinkedList returns a NullPointerException

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,
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 =;

while (i < size) {
if (i == index) {

System.out.println("Removing " + + " from the list"); = currentNode.prev; =;


currentNode =;

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!

Answer Source

I think the issue you are having is from this line: = currentNode.prev;

If the index to be removed is the last item in the list (e.g. index == size() - 1), it will satisfy the loop conditions and the above code would execute. However, since it is the last element in the list, the is null. The line above is calling the .prev on a null value which results in the null pointer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download