簡體   English   中英

刪除Java中LinkedList實現的方法

[英]Remove method for linkedList implementation in Java

我從演講中linkedListspecified index處從linkedList中刪除元素的方法。 我了解該方法的工作原理,但是我不明白為什么for-loop會在current node pointer索引之前將current node pointer留在兩個索引之前。

方法如下:

public void remove(int index) {
        if (index == 0) {
            // removing the first element must be handled specially
            front = front.next;
        } else {
            // removing some element further down in the list;
            // traverse to the node before the one we want to remove
            ListNode current = front;
            for (int i = 0; i < index - 1; i++) {
                current = current.next;
            }

            // change its next pointer to skip past the offending node
            current.next = current.next.next;
        }
    }

for-loop0 to < index-1 ,而我認為應該從0 to < index 這樣一來,指針是一個index的前index需要加以刪除。 但是,上述方法可以正常工作。

例如:在下面的LinkedList 在此處輸入圖片說明

讓我們考慮刪除Node C 通過上面的循環構造, current pointer將指向Node Acurrent.next將指向Node B current.next.next將是Node C 進行current.next=current.next.next將導致Node B而不是Node C刪除。

我認為我的理解有問題,有人可以解釋嗎?

for循環從0到<index-1

在您的示例中,刪除C表示index為2 所以i只去0 ,因為1< 1

currentA開始, for循環一次, current到達B

currentB ,所以current.next.nextD ,這有效地刪除了C

暫無
暫無

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

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