简体   繁体   English

链表中间

[英]Middle of the Linked List

In the code below, when using two pointers technique, it's confusing that why we use slow.next and fast.next.next.在下面的代码中,当使用两个指针技术时,为什么我们使用 slow.next 和 fast.next.next 令人困惑。 For example in the linked list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], if we are in the last position '10' (fast pointer), the slow pointer should be in the '8' position.例如在链表[1,2,3,4,5,6,7,8,9,10]中,如果我们在最后一个position'10'(快指针),慢指针应该在'8' position。 Could someone please clarify that?有人可以澄清一下吗?

def middleNode(self, head):
        slow = fast = head 
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            
        return slow

In short: fast moves at double speed of slow .简而言之: fastslow两倍速度移动。 Their distance increases at each iteration by one.它们的距离在每次迭代时增加一。 This is different than moving with the same velocity but starting different positions (say one starts at 0 and the other at 2).这与以相同速度移动但开始不同位置(例如一个从 0 开始,另一个从 2 开始)移动不同。

More detailed explanation:更详细的解释:

The fast pointer moves with double the speed of the slow pointer, that's why when the fast pointer reaches the end of the linked list, the slow pointer is in the middle. fast指针的移动速度是慢指针的两倍,这就是为什么当fast指针到达链表末尾时, slow指针在中间。 That's the reason why the fast pointer moves fast.next.next .这就是fast指针移动fast.next.next的原因。 This means that fast skips one and jumps 2 fields in each iteration, while the slow pointer only moves one.这意味着fast在每次迭代中跳过一个并跳转2个字段,而slow指针只移动一个。 That's also the reason you check fast and fast.next in the while loop condition, to make sure the next pointer is not None , because you want to call next on it.这也是您在while循环条件中检查fast and fast.next的原因,以确保next指针不是None ,因为您想在其上调用next

Let's take a smaller example then you have provided to make illustration easier:让我们举一个较小的示例,然后您提供以使说明更容易:

[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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM