Deploying duplicate list from scratch, error in remove () method

I tried to learn how to implement the Doubly Linked List in java as an exercise. but I am stuck in a method remove().

List Content:

1 2 3 4

When I try to remove an item that is not present. It shows NullPointerExceptionat line no. 21instead of printing not found.

The other codes I saw were a bit complicated and different from what I am doing. Method:

 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 this completely wrong? OR what is the problem? Forgive me if this is too stupid.

+4
source share
2 answers

. while "n.d == data" . "n.d!= Data" i.e.

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

:

...

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

:

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;
    }       
}
+2
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;
        }
    }
}
0

Source: https://habr.com/ru/post/1622436/


All Articles