Find the Middle Node of a Linked List

Implement middleNode

Given the head of a singly linked list, return the middle node. If the list has two middle nodes (an even count), return the second one. Since a linked list has no length property, finding "the middle" naively means counting first. The optimal solution avoids that entirely with a fast and slow pointerFast & Slow PointersTwo pointers start together but move at different speeds — typically one step vs. two steps per iteration. Because the faster one covers exactly double the distance, its position relative to the end tells you something useful about the slower one's position — here, that it's sitting on the middle. — by the time fast has covered the whole list, slow has covered exactly half of it.

Example 1:

Input: head = [1,2,3,4,5]

Output: [3,4,5]

Example 2:

Input: head = [1,2,3,4,5,6]

Output: [4,5,6]

Example 3:

Input: head = [1]

Output: [1]

+ 5 hidden test cases run on Submit.

Constraints:

  • 1 ≤ number of nodes in head ≤ 10⁴
  • -10⁹ ≤ node value ≤ 10⁹
  • For an even-length list, return the second of the two middle nodes

head =

[1, 2, 3, 4, 5]