2014-01-06 65 views
1

我從講座中刪除了linkedList中的元素specified index。 我明白該方法是如何工作的,但我不明白爲什麼for-loop在所需的索引之前離開current node pointer兩個索引。刪除Java中linkedList實現的方法

這裏是方法:

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處。但是,上述方法正常工作。

對於如: 在下面LinkedListenter image description here

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

我覺得我的理解有些問題,有人能解釋嗎?

回答

1

的for循環從0到<索引-1

在您的例子,除去C意味着索引是2。所以i只能去0,因爲1不是< 1

currentA開始,for循環一次,current進入B

currentB,所以current.next.nextD,它有效地消除C

+0

根據這個循環,我們考慮一個包含10個元素的鏈表。如果我想刪除'index 5'元素,我的'當前指針'將在'index 3',但我認爲它應該在'index 4'去除下一個? –

+0

@ user1988876刪除索引5(第6個元素)意味着移動光標「5-1」次。遊標然後將在被移除之前的元素處。 –

+1

remove [index 5],循環從0 <4 [0,1,2,3]四次,然後當前指向[index 4],因此current.next.next指向[index 6],while current.next = current.next.next將[index 6]加入[index 4的尾巴],沒錯。 – wangdq