Learn how to find the middle node of a linked list using the fast and slow pointer technique through interactive visualization.
About this algorithm
To find the middle node of a singly linked list in one walk, move two pointers from the head: slow takes one step at a time and fast takes two. When fast reaches the end, slow has covered half the distance and is standing on the middle node.
Use fast and slow pointers when you need the middle without knowing the length: splitting a list in half for merge sort, checking whether a list is a palindrome by reversing its second half, or choosing the root when building a balanced tree from a sorted list. Counting the length and then walking to L / 2 gives the same answer in two walks and is fine when clarity matters more. The same two-speed idea, run on a list that may loop, is the cycle check on the Circular and Cycle pages.
Set slow and fast to the head. An empty list has no middle.
Loop while fast is not null and fast.next is not null. This check is what stops fast from stepping off the end.
Move slow to slow.next and fast to fast.next.next.
When the loop stops, slow is on the middle. With an odd number of nodes that is the exact middle. With an even number, this loop leaves slow on the second of the two middle nodes; to get the first one instead, loop while fast.next and fast.next.next are not null.
The page loads 10, 20, 30, 40, 50, 60, 70. Both pointers start on 10. Round 1: slow 20, fast 30. Round 2: slow 30, fast 50. Round 3: slow 40, fast 70. Now fast.next is null, so the loop stops after 3 rounds with slow on 40, the 4th of 7 nodes, three on each side. With an eighth node, 80, on the end, round 4 would take fast past 80 to null and leave slow on 50, the second of the two middle nodes 40 and 50.
After k rounds slow has moved k nodes and fast has moved 2k. Fast runs out when 2k reaches about the length L, so k is about L / 2, which is exactly where slow is standing.
Time: the loop runs about N / 2 rounds, with fast crossing the whole list once, so O(N). Space: two pointers, so O(1).