在下面的代碼中,當使用兩個指標技術時,我們會混淆為什么使用slow.next 和fast.next.next。例如在鏈表[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]中,如果我們在最后一個位置'10'(快指標),慢指標應該在“8”位。有人可以澄清一下嗎?
def middleNode(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
uj5u.com熱心網友回復:
簡而言之: fast以 的兩倍速度移動slow。它們的距離在每次迭代中增加一。這與以相同速度移動但從不同位置開始(假設一個從 0 開始,另一個從 2 開始)不同。
更詳細的解釋:
該fast指標移動與緩慢的指標的兩倍速度,這就是為什么當fast指標到達鏈表的結尾,slow指標是在中間。這就是fast指標移動的原因fast.next.next。這意味著fast在每次迭代中跳過一個并跳轉 2 個欄位,而slow指標只移動一個。這也是你檢查原因fast and fast.next在while回圈條件,以確保next指標不是None,因為你要呼叫next就可以了。
讓我們舉一個比您提供的更小的示例,以便更容易地說明:
[1,2,3,4,5]
# before entering the while loop:
# head is at position 1
# fast and slow both are at position 1
# first iteration
[1,2,3,4,5]
f
s
fast == 1 and fast.next == 2
slow == 1
fast jumps 2 nodes and becomes 3 (fast.next.next)
slow jumps 1 node and becomes 2 (slow.next)
# second iteration
[1,2,3,4,5]
f
s
fast == 3 and fast.next == 4
slow == 2
fast jumps 2 nodes and becomes 5 (fast.next.next)
slow jumps 1 node and becomes 3 (slow.next)
# third iteration (doesn't enter the loop, see why)
[1,2,3,4,5]
f
s
fast == 5 and fast.next == None (tail of linked list)
slow == 3
# while loop breaks
# we return slow which lies in the middle of the linked list
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/387600.html
上一篇:CPLEXOPL錯誤運行時:不要輸入lloType,
下一篇:用int對char求和的C程式
