链表中间节点算法中为何需同时判断fast与fast.next作为循环终止条件?
fast and fast.next in the Loop Condition Looking at your code for finding the middle node of a linked list:
class Solution(object): def middleNode(self, head): """ :type head: ListNode :rtype: ListNode """ slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow
Great question—this is a common point of confusion with the slow-fast pointer technique, so let's break this down clearly.
First: Why just while fast.next isn't safe
Let's test two common linked list scenarios to see the difference:
1. Odd-length linked list (e.g., 1 → 2 → 3 → 4 → 5)
When we reach the final iteration, fast will land on the last node (value 5). At this point, fast.next is None, so while fast.next would terminate correctly—no issues here.
2. Even-length linked list (e.g., 1 → 2 → 3 → 4)
After the second loop iteration, fast will become None (here's why: starting from node 3, we do fast = fast.next.next—3.next is 4, 4.next is None, so fast ends up as None). Now, if our loop condition was just while fast.next, we'd try to access None.next—which throws an AttributeError because None doesn't have a next attribute. That's a crash we absolutely want to avoid!
By using while fast and fast.next, we leverage Python's boolean short-circuit evaluation: we first check if fast is not None. If it is None, the condition immediately fails without trying to access fast.next, preventing the error.
Second: Is your understanding correct?
Your statement "if fast.next is None, then fast must be None" is not correct.
Think about the last node in any non-empty linked list: the node itself exists (so fast points to it, meaning fast is not None), but its next pointer is None (since it's the end of the list). So here, fast.next is None, but fast is definitely a valid node. That's exactly the scenario we hit with odd-length lists, and it's why we need both checks—we have to handle cases where fast is a valid node with no next node, and cases where fast has already become None.
Quick Recap
- Check
fastfirst: Prevents trying to accessnexton aNonevalue (critical for even-length lists). - Check
fast.next: Stops the loop when we can't movefastforward twice anymore (handles the end of odd-length lists).
内容的提问来源于stack exchange,提问作者klme

