Middle of the Linked List

Find the middle node in one pass using the speed-1 / speed-2 pointer pair.

Easy
Time O(n) Space O(1)
LeetCode
2 min read
fast-slow linked-list

Problem#

Given the head of a singly linked list, return the middle node. For even-length lists, return the second of the two middles.

Examples#

  • [1,2,3,4,5] → node 3
  • [1,2,3,4,5,6] → node 4

Constraints#

  • List length in [1, 100].

Approach#

slow advances one step, fast advances two. When fast reaches the end, slow is at the middle.

Solution#

Middle of the Linked List
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};

Editorial#

For even-length n, fast lands on nullptr after n/2 iterations and slow is at index n/2 (the second middle). For odd n, fast lands on the last node and slow is at index (n-1)/2. No length precomputation needed — the speed ratio carries the bookkeeping.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.