java双向链表删除一个节点

时间:2015-04-14 00:59:49

标签: java doubly-linked-list

我得到了一个名为key的整数作为参数。我需要知道如何删除位置键上的节点。 Ndata来自我的Node类。

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

2 个答案:

答案 0 :(得分:1)

假设您需要找到存储值key的节点,您需要执行以下任一操作:

Node<Integer> temp = head;

或:

public void deleteNode(E key)

这可确保您的通用Node类的类型兼容性。

答案 1 :(得分:1)

正如您所提到的,您需要删除key位置的节点。以下是代码的编写方式:

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
}

希望这会对你有所帮助。