Middle of a Linked List
L6 Medium Linked List
Concept
Two pointers moving at different speeds find the midpoint of a linked list without ever counting its length.
Given the head of a singly linked list, return the node at the middle. If there are two middle nodes (even length), return the second one.
Examples
▸ head = [1, 2, 3, 4, 5]
→ [3, 4, 5]
▸ head = [1, 2, 3, 4]
→ [3, 4]
▸ head = [1]
→ [1]
Progressive Hints
Hint 1 · Nudge
Race two pointers: one runs twice as fast, and you wait for it to finish.
Hint 2 · Plan
Move a slow pointer one step and a fast pointer two steps each loop. When the fast pointer reaches the end, the slow pointer is at the middle, and even lengths naturally give the second middle.
Hint 3 · Approach
slow = head, fast = head. While fast and fast.next exist: slow = slow.next; fast = fast.next.next. Return slow.
All hints are out. Take a breath and give it a shot.
Output
// Run your code to see the output here.