What does it solve?
Find the middle node of a linked list. The obvious way needs two passes: count the length N, then walk N/2 again. The slow/fast trick finds it in a single pass, without ever knowing the length up front.
Key insight: move slow one node and fast two nodes each step. Fast covers the list twice as quickly, so when fast falls off the end, slow has travelled exactly half the distance: it's on the middle. For an even length the loop condition decides which of the two middles you land on: while fast && fast.next gives the second middle (LeetCode's answer).
The core idea
slow = head, fast = head
while fast && fast.next:
slow = slow.next
fast = fast.next.next
return slow
Complexity
Fast reaches the end in about N/2 steps, and that's the whole run. One pass, no length precomputation.
Two pointers, nothing else. No array copy, no length counter beyond the pointers themselves.
Lists & edge cases
Step-by-step table
| Step | slow idx | slow val | fast idx | fast val | fast ended? |
|---|
C++ implementation
#include <bits/stdc++.h> using namespace std; struct ListNode { int val; ListNode* next; }; // Slow/fast: when fast falls off the end, slow is the middle. ListNode* middleNode(ListNode* head) { ListNode* slow = head; ListNode* fast = head; while (fast && fast->next) { slow = slow->next; // one step fast = fast->next->next; // two steps } return slow; // even length -> the SECOND middle }
My Notes