Reverse Linked List

EasyLinked lists

You get the head of a singly linked list. Reverse the list and return its new head.

Each node has a val and a next pointer, and the last node’s next is null. On this page a list is written as an array of its values, from head to tail.

Examples

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

The links now run the other way, so 4 is the head.

Example 2
Input:  head = [7, 8]
Output: [8, 7]

Two nodes swap places.

Constraints

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

Stuck?

Hint 1

Walk the list once and turn each next pointer around as you pass it. You need to remember the node before the current one.

Hint 2

Keep three names: previous, current, and the next node you are about to lose. Recursion works too, but it uses O(n) stack.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 8 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur