Chewy
Chewy

Reputation: 11

java doubly linked list delete a node

I was given an integer called key as the parameter. I need to know how to delete a node at position key. Ndata is from my Node class.

    public void deleteNode(int key)
    {
       Node<E> temp = head; 
       while(temp.Ndata != key)//gives me error as not compatible types.    
       {
            temp = temp.next;
       }
       if(temp == head)
            head = temp.next;
       else
            temp.prev.next = temp.next;
       if(temp == tail)
            tail == temp.prev;
       else
            temp.prev.next = temp.next;
     }

Upvotes: 0

Views: 2847

Answers (2)

Prit
Prit

Reputation: 31

As you mentioned that, you need to delete a node at position key. Here is how the code should be:

public void deleteNode (int key) {
    // those are base cases
    if (key >= length)
        key = length - 1;
    elseif (key < length)
        key = 0;

    if (head == null) // if list is empty
        return;

    if (key == 0){ // it means you have to remove head
        head = head.getNext(); //assuming you have getters and setters
        if (head == null)
            tail = null;
    } else {
        Node<E> temp = head;
        // iterate to that position ie. key
        for (int index = 0; index < key; index++){
            temp = temp.getNext();
        }
        // this is most important part
        temp.getNext().setPrev(temp.getPrev());
        temp.getPrev().setNext(temp.getNext());
    }
    length--; //since you deleted element the list is now 1 less
}

Hope this helps you.

Upvotes: 1

egracer
egracer

Reputation: 362

Assuming that you need to find the node which is storing the value key, you need to do either:

Node<Integer> temp = head;

or:

public void deleteNode(E key)

This ensures type compatibility for your generic Node class.

Upvotes: 1

Related Questions