Skip to content
Optimal Lab

Linked List · 020Easy

Reverse Linked List

Given the head of a singly linked list, reverse the list and return the new head. A node is { val, next }.

Constraints

  • The list holds 0 to 5000 nodes.
  • -5000 <= Node.val <= 5000
  • INPUT FORMAT
  • `head` is a ListNode object, not an array. The arrays in EXAMPLES list the node values in
  • order; the test runner links them into real nodes before calling your function.

Examples

reverseList(1 -> 2 -> 3 -> 4 -> 5)  ->  5 -> 4 -> 3 -> 2 -> 1
reverseList(1 -> 2)                 ->  2 -> 1
reverseList(null)                   ->  null
reverseList(1)                      ->  1   // a single node is its own reverse
reverseList(-3 -> 0 -> 3)           ->  3 -> 0 -> -3   // negatives
reverseList(7 -> 7 -> 7)            ->  7 -> 7 -> 7   // duplicates look unchanged

Edge cases

  • Empty list.
  • Single node.
  • FOLLOW-UP
  • A linked list can be reversed either iteratively or recursively. Could you implement both?
Show the target complexity (spoiler)
Naive
O(n) time, O(n) space — copy values into an array and rebuild.
Target
O(n) time, O(1) space — iterate with prev/curr/next pointers, re-linking as you go.

Solve it

By hand, in your editor. The runner checks answers and timing.

git clone https://github.com/sarmadkung/optimal-round
cd optimal-round
# open problems/06-linked-list/020-reverse-linked-list.js
./practice c 020

Stuck? Watch the pattern run