簡體   English   中英

LinkedList刪除方法

[英]LinkedList remove method

什么是雙向鏈表的刪除方法?

蜥蜴比爾說的算法相同,但以圖形方式:-)

從鏈接列表中刪除
(來源: jaffasoft.co.uk

一般算法如下:

  • 找到要刪除的節點。
  • node.previous.next = node.next
  • node.next.previous = node.previous
  • node.previous = null
  • node.next = null
  • 如果您處於非GC環境中,請處置節點

您必須檢查上一個和下一個節點是否為null,以查看是否正在移除頭部或尾部,但這些是容易的情況。

public void remove ()
{
    if (getPreviousNode () != null)
        getPreviousNode ().setNextNode (getNextNode ());
    if (getNextNode () != null)
        getNextNode ().setPreviousNode (getPreviousNode ());    
}

雙鏈表實現刪除方法(來自我的第二個編程任務):

public void remove(int index) {
    if(index<0 || index>size())
    throw new IndexOutOfBoundsException("Index out of bounds. Can't remove a node. No node exists at the specified index");
    if(size()==0) {
        throw new NullPointerException("Empty list");
    }
    if(!isEmpty()) {
        Node current;
        //starting next one to our head
        current = head.next;
        for(int i=0;i<index;i++) {
            current = current.next;
        }
        current.previous.next = current.next;
        current.next.previous = current.previous;
        numOfNodes--;
        sizeChangeCount++;
    }
}

public boolean remove(T o) {
    Node current = head;
    for(int i=0;i<size();i++) {
        current=current.next;
        if(current.data.equals(o)) {
            current.previous.next = current.next;
            current.next.previous = current.previous;
            numOfNodes--;
            sizeChangeCount++;
            return true;
        }           
    }
    return false;
}

你在api中要求一個方法的名字嗎? 假設您詢問的是java.util.LinkedList實際上是一個雙鏈表,那么這個答案就會被刪除。

...或者您是在詢問從該類型的數據結構中刪除元素的算法名稱是什么? 嗯..答案也是刪除一個元素。 現在對於實際算法來說......它實際上只是改變前一節點中的下一個指針和下一個節點中的最后一個指針。 但是,如果從多個線程使用數據結構,則需要同步remove方法,或者按照對數據結構的使用模式有意義的順序執行刪除步驟。

那么當前的指針指針呢? 你必須將crnt移動到下一個節點。 http://pastebin.ca/1249635

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM