Given the
Output: [3, 4, 5]
Explanation: The middle node has value 3. Returning node 3 and everything after it.
Output: [4, 5, 6]
Explanation: With 6 nodes there are two middle nodes (3 and 4). The second middle node (value 4) is returned.
The classic approach is to use two pointers where
- Initialize both
slow andfast athead . - While
fast != null andfast.next != null , advanceslow by 1 andfast by 2. - When the loop ends,
slow is at the middle node. For even-length lists, this naturally gives the second middle. - Return
slow .
Complexity Analysis:
Time complexity: O(n) where n is the number of nodes. The fast pointer traverses the list in n/2 iterations.
Space complexity: O(1) since only two pointer variables are used.