AlgoFrames

Middle node

Warm-up · Write code · about 6 min

Given the head of a non-empty singly linked list, return its middle node. With an even number of nodes there are two middles; return the second one.

The answer is shown as the list that starts at the returned node.

Example 1

Input:

[[1,2,3,4,5]]

Output:

[3,4,5]

Example 2

Input:

[[1,2,3,4,5,6]]

Output:

[4,5,6]

3 and 4 are both middles; return 4.

Constraints

  • 1 ≤ number of nodes ≤ 5,000
  • 1 ≤ node value ≤ 10,000

Learn the idea first: Linked list techniques: reverse, middle, merge, detect a cycle, a visual lesson.

More Linked list techniques: reverse, middle, merge, detect a cycle problems