Home > Back-end >  Delete node from anywhere in a doubly linked list
Delete node from anywhere in a doubly linked list

Time:09-15

I would like to delete a node from anywhere in a doubly linked list. But I hit an exception error. Could anyone help to solve the problem? Error Message sample

public void delete(T data) {
    /* if the list is not empty */
    if (!isEmpty()) {
        if (this.head == this.tail && data == this.head.data) {
            this.tail = this.head = null;
        } else if (this.head.data == data) {
            this.deleteFromStart();
        } else {
            DllNode temp = this.head;
            for (; temp != null & temp.data != data; temp = temp.next);

            if (temp != null) {
                if (temp == this.tail) {
                    this.deleteFromEnd();
                } else {
                    temp.prev.next = temp.next;
                    temp.next.prev = temp.prev;
                }
            }
        }

    }
}

CodePudding user response:

It seems that the error is in last line when temp.next = null so temp.next.prev will break. So you need to check if doesn't equal null before you access temp.next.prev.

Another point is try to avoid nested if conditions. I refactored your code as below, but I didn't tested as you didn't share your class and the main function you used.

public void delete(T data) {
    /* if the list is not empty */
    if (isEmpty()) return;
    if (this.head == this.tail && data == this.head.data) {
        this.tail = this.head = null;
        return;
    }  
    if (this.head.data == data) {
        this.deleteFromStart();
        return;
    } 
    DllNode temp = this.head;
    for (; temp != null & temp.data != data; temp = temp.next);
    if (temp == null) return;
    if (temp == this.tail) {
        this.deleteFromEnd();
        return;
    } 
    temp.prev.next = temp.next;
    if(temp.next == null) return;
    temp.next.prev = temp.prev;
}
  • Related