itishrishikesh
itishrishikesh

Reputation: 326

Implementing Doubly Linked List from scratch, error in remove() method

I was trying to learn to implement Doubly Linked List in java just as an exercise. but I am stuck at remove() method.

The contents of the list are,

1 2 3 4

When I try to remove the element which is not present.It shows the NullPointerException at line no. 21 instead of printing not found.

The other codes that I saw was a little complicated and different from what I am doing. The method is,

 void remove(int data){
    Node n = head;
    if(head==null)
        System.out.println("Not Found");
    else if(head.d==data){
        if(head==tail){
            head=null;
            tail=null;
        }
        else{
            head=head.next;
            head.prev=null;
        }
    }
    else{
        while(n!=null && n.d==data){
            n=n.next;
        }
        if(n==tail){
            tail=tail.prev;
            tail.next=null;
        }
        else if(n!=null){
            n.prev.next=n.next;
            n.next.prev=n.prev;
        }
        if(n==null)
            System.out.println("Not Found");
    }
}

So my Question is, Am I doing it completely wrong? OR what is the problem? Pardon me if it's just too foolish.

Upvotes: 4

Views: 204

Answers (2)

raj kumar
raj kumar

Reputation: 101

The problem is with search logic. In the while loop condition "n.d == data" is incorrect. It should be "n.d != data" i.e.

while(n!=null && n.d==data){
n=n.next;
}

Should be:

...

    while(n!=null && n.d != data){
        n=n.next;
    }

Here is a much cleaner implementation :

public void remove(int data) { // Head is not required in param, should be field variable
    Node ptr = head;

    while(ptr!=null && ptr.data != data) // search for the node
    {
        ptr = ptr.next;
    }

    if(ptr == null) {
        System.out.println("Not Found");
        return;
    }

    if(ptr.prev == null) {// match found with first node
        head = ptr.next;
    }
    else{
        ptr.prev.next = ptr.next;
    }
    if(ptr.next == null){// match found with last node
        tail = ptr.prev;
    }
    else{
        ptr.next.prev = ptr.prev;
    }       
}

Upvotes: 2

lucky
lucky

Reputation: 164

void remove(Node head, int value) {
    if (head == null) {
        System.out.println("Not Found");
    } else if (value == head.d) {
        if (head == tail) {
            head = null;
            tail = null;
        } else {
            head = head.next;
            head.prev = null;
        }
    } else {
        Node n = head.next;
        while (n != null && value != n.d) {
            n = n.next;
        }
        if (n == tail) {
            tail.next = null;
            tail = tail.prev;
        } else if (n != null) {
            n.prev.next = n.next;
            n.next.prev = n.prev;
        }
    }
}

Upvotes: 0

Related Questions