2011-03-13 41 views
1

如何交換鏈表的最後兩個節點?我試圖使用一個輔助節點,因爲我認爲這是需要避免的過程中「丟失」的一個節點......交換單鏈表的最後兩個節點

... 
Node node3 = new Node("Hi", null) ; 
Node node4 = new Node("Hello", null) ; 
... 

// swap node3 & node4 
Node temp = node3.succ ; 
node3.succ = null ; // this should be the last node now, so i set its pointer to null 
node2.succ = temp ; // the second's node successor becomes what used to be the last node 
temp = node4 ; // not sure how to use temp here. what should it point to if at anything? 

我覺得我這樣做不對,任何提示?

回答

4

假設你有一個鏈表A -> B -> C,並且要交換BC

  1. 集T * = B(存儲器B某處)
  2. 設置A.next = C
  3. 套裝T *的.next = C.next(此概括這從剛剛在列表的末尾操作)
  4. 集C.next = T *
+0

非常感謝你! – raoulbia

1

這看起來像是單鏈表。您需要讓node4繼承node2(節點的後繼node3)。您還需要使node3繼承node4。所以:

  1. 獲取引用node2node3,並node4
  2. 設置node2.succnode4
  3. 設置node4.succnode3
  4. 設置node3.succnull

你可以做到這一點更簡單/如果你沒有明確地抓住,那麼有效(儘管不太清楚)引用所有3個節點,但這應該讓你開始。

0

您實際上必須跟蹤三個節點 - 您將切換的最後兩個節點,以及一個前面的節點,以便您可以更新它的指針。

或者,您可以交換節點值。

1

好,你已經得到了正確的答案:-)

溫度和節點4引用同一個對象。所以你已經成功交換了它們。你現在可以讓溫度超出範圍(即保持不變)。

所以你不需要設置任何東西的溫度。

相關問題