0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.