-1

I have a remove method , find the element in that list and delete it.That topic is about Doubly linked list.Is my operation true in if and else if statement for the formation of the new list?

public void Remove(int key) {//key = number in the list.
        if (head == null) {
            System.out.println("Empty List..!");
        } else if (key == head.key) {
            head.prev.next = head.next;
            head.next = null;
            noOfNodes--;
        } else if (key == tail.key) {
            tail.next.prev = tail.prev;
            tail.prev = null;
            noOfNodes--;
        } else {
            for (LinkedListNode temp = head; temp.next != null; temp = temp.next) {
                if (temp.key == key) {
                    temp.prev.next = temp.next;
                    temp.next.prev = temp.prev;
                    temp.prev = null;
                    temp.next = null;
                    noOfNodes--;
                }
            }
        }
    }
ZpCikTi
  • 115
  • 1
  • 11
  • 2
    Do you have a question? – breen Nov 18 '15 at 20:17
  • @LawrenceAiello I edited. Sorry about that. – ZpCikTi Nov 18 '15 at 20:19
  • Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Seelenvirtuose Nov 18 '15 at 20:23
  • This might be the issue `tail.next.prev = tail.prev;`. Are you sure `tail.next` is not null? Isn't `tail` the last element of your doubly linked list? – Atri Nov 18 '15 at 20:32
  • @ashutosh You are absolutely right. Thanks for your comment. I corrected my code thanks to you. – ZpCikTi Nov 19 '15 at 14:02

1 Answers1

0

From your code, it looks like tail is the last node of your linked list.

So, this might be the issue tail.next.prev = tail.prev;. Since tail.next is null as tail is the last element, when you access prev on tail.next it throws NullPointerException.

Atri
  • 5,051
  • 5
  • 28
  • 39