AlgoFrames

Reverse a list

Warm-up · Write code · about 8 min

Given the head of a singly linked list, reverse it in place and return the new head. Do not create new nodes; turn the arrows around.

Example 1

Input:

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

Output:

[5,4,3,2,1]

Example 2

Input:

[[]]

Output:

null

An empty list stays empty (null).

Constraints

  • 0 ≤ number of nodes ≤ 5,000
  • -5,000 ≤ node value ≤ 5,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