Problem
Section titled “Problem”Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Example 1:

Input: head = [1,2,3,4,5]Output: [3,4,5]Explanation: The middle node of the list is node 3.Example 2:

Input: head = [1,2,3,4,5,6]Output: [4,5,6]Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.Constraints:
- The number of nodes in the list is in the range
[1, 100].
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”Counting the nodes and then walking count / 2 steps works, but needs two passes. We can do it in one with the slow and fast pointer (tortoise and hare) technique: slow moves one node per step and fast moves two. When fast runs off the end of the list, slow has covered exactly half the distance, so it is standing on the middle.
Invariant: after k steps, slow is node k and fast is node 2k (0-indexed). The loop stops at the first k for which node 2k or node 2k + 1 does not exist, i.e. k = floor(n / 2) — which is the middle for odd n and the second middle for even n, exactly what the problem asks.
Algorithm
Section titled “Algorithm”- Set
slow = fast = head. - While
fastandfast->nextboth exist:slow = slow->next,fast = fast->next->next. - Return
slow.
Walkthrough
Section titled “Walkthrough”Example 2, with slow in blue and fast in orange (the trailing null is where fast falls off the list):
Complexity
Section titled “Complexity”- Time: —
fastvisits about every second node, so the loop runs times in a single pass. - Space: — two pointers.
Edge cases
Section titled “Edge cases”- Single node:
fast->nextis null, the loop never runs andheadis returned. - Even length: the loop stops when
fastbecomes null (not whenfast->nextis null), which leavesslowon the second middle, as in Example 2.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { public: ListNode* middleNode(ListNode* head) { ListNode* slow = head; ListNode* fast = head; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; } return slow; }};class Solution { public ListNode middleNode(ListNode head) { ListNode slow = head; ListNode fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; }}class Solution: def middleNode(self, head: ListNode | None) -> ListNode | None: slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slowGive it a try first
Attempt the problem on LeetCode — the code will still be here.




