[英]Remove method for linkedList implementation in Java
我從演講中linkedList
從specified 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-loop
從0 to < index-1
,而我認為應該從0 to < index
。 這樣一來,指針是一個index
的前index
需要加以刪除。 但是,上述方法可以正常工作。
例如:在下面的LinkedList
讓我們考慮刪除Node C
通過上面的循環構造, current pointer
將指向Node A
而current.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
。
current
從A
開始, for
循環一次, current
到達B
current
是B
,所以current.next.next
是D
,這有效地刪除了C
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.