The βMiddle of the Linked Listβ problem asks us to return the middle node of a singly linked list. If the list has an even number of nodes, we are required to return the second middle node.
Example:
1 β 2 β 3 β 4 β 5
3
1 β 2 β 3 β 4 β 5 β 6
4
This problem introduces one of the most elegant applications of the two-pointer technique β a method used in many advanced linked list problems. Understanding how to find midpoints with pointers builds a foundation for more complex challenges like palindrome checking, cycle detection, and list reordering.
The best way to find the middle node of a singly linked list in a single pass is to use two pointers:
When the fast pointer reaches the end of the list, the slow pointer will be at the midpoint.
slow
and fast
pointers at the head of the list.fast != null
and fast.next != null
:slow = slow.next
fast = fast.next.next
slow
will be pointing to the middle node.slow
.
Input: 1 β 2 β 3 β 4 β 5
Iteration steps:
For even-length list: 1 β 2 β 3 β 4 β 5 β 6
β returns node 4 (the second middle).
Time Complexity: O(n), where n is the number of nodes. Each node is visited at most once.
Space Complexity: O(1), as we use only two pointers.
The βMiddle of the Linked Listβ problem is a classic use of the slow and fast pointer technique. It's a clean and efficient solution that runs in linear time without needing to count nodes or use extra memory. Mastering this strategy will benefit you in numerous other linked list-related problems.