Reputation: 261
I'm trying to work on a remove function for a doubly linked list, but I keep getting a Null Pointer exception on the current.prev.next = current.next;
part. I don't think I really understand what a null pointer exception is, because I have no idea what to do to fix this. The log function is just one I wrote to write to an output file, and retval[1] is the element I'm searching to delete.
Node current = head;
while(current != null)
{
if((current.data).compareTo(retval[1]) == 0)
{
if(current.prev == null)
head = current.next;
if(current.next == null)
tail = current.prev;
current.prev.next = current.next;
current.next.prev = current.prev;
current = null;
valid++;
log(line + "\n" + "Sucsessfully Removed \n");
}
else
{
log(line + "\n" + InvalidTransaction + " - Element does not exist \n");
}
current = current.next;
}
I'm sure it's something stupid, but I don't know what it is. Any help would be greatly appreciated.
Upvotes: 0
Views: 2610
Reputation: 628
Just replace
current.prev.next = current.next;
current.next.prev = current.prev;
with
if(null != current.prev) current.prev.next = current.next;
if(null != current.next) current.next.prev = current.prev;
And also you need to break the loop once the element is found.
Upvotes: 1
Reputation: 16987
A NullPointerException
means that you tried to do something with an object that was null
. Since current
definitely wasn't null
, then current.prev
must have been null
. Go from there.
Upvotes: 0