Skip to the code
cf.
+10 XP

#239 Reverse the Undo Chain

easy

A drawing app keeps its edit history as a linked list from the newest edit to the oldest. The history panel wants to show it oldest first.

Write reverseHistory(head) that reverses the list in place by relinking its nodes and returns the new head.

Example 1

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

The last edit becomes the first.

Example 2

Input: head = [1,2]
Output: [2,1]

Two nodes simply swap order.

Constraints

  • The list has 0 to 5000 nodes.
  • -5000 <= node.val <= 5000

Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).