简体   繁体   中英

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;
     }

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM