Skip to main content
19

Reverse Linked List

Easylinked list

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Linked ListRead the beginner guide

Given the head of a singly linked list, reverse the list and return the new head.

Understand the problem

  • A linked list is a chain of nodes. Each node holds a value (val) and a pointer to the next node (next). The last node's next is null (None in Python). (New to linked lists? Read the beginner guide linked at the top.)
  • The head is the first node. You only get the head, and you reach the rest by following next.
  • Reversing means making every arrow point the other way, so the old last node becomes the new head.
Loading diagram...

In the tests, a list is written as an array: [1, 2, 3] means 1 → 2 → 3, and [] is an empty list (null / None).

Example 1

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

Example 2

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

Example 3

text
Input:  head = []
Output: []

An empty list reversed is still empty.

Constraints

  • 0 <= number of nodes <= 5000
  • -5000 <= Node.val <= 5000

Note

Follow-up: can you do it both with a loop and with recursion?

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Walk through the list once and flip each node's arrow to point backward, remembering the next node before you flip so you don't lose the rest of the list.

    The naive approach (and its cost)

    Copy all the values into an array, reverse the array, then build a brand-new list (or write the values back). It works, but it uses O(n) extra memory for the array, and it dodges the real skill being tested: rewiring pointers.

    The key insight

    A linked list is just nodes connected by arrows (next). Reversing doesn't require moving anything: flip every arrow.

    The catch: each node only knows about the node after it. When you flip current.next to point backward, you lose your only way forward. So you need three pointers:

    • prev: the node behind you (already reversed). Starts as null, because the old head becomes the new tail.
    • current: the node you're flipping now.
    • next: a bookmark to the rest of the list, saved before flipping.

    Step by step

    1 → 2 → 3 → null:

    StepprevcurrentSave nextFlip (current.next = prev)List so far
    startnull11 → 2 → 3 → null
    1null121 → nullnull ← 1 2 → 3 → null
    21232 → 1null ← 1 ← 2 3 → null
    323null3 → 2null ← 1 ← 2 ← 3
    end3nullreturn prev = 3

    After each step, move forward: prev = current, current = next.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). Each node is visited once.
    • Memory: O(1). Just three pointers, no matter how long the list is.

    Common mistakes

    • Not saving next before flipping. After current.next = prev, current.next no longer leads forward, and the rest of the list is lost.
    • Returning head or current. At the end, head is the new tail and current is null. The new head is prev.
    • Forgetting the empty list. With head = null, the loop never runs and prev = null is correctly returned.

    Going deeper

    The recursive version: reverse everything after head, then attach head at the end:

    js
    function reverseList(head) {
      if (!head || !head.next) return head // 0 or 1 node: already reversed
      const newHead = reverseList(head.next) // reverse the rest
      head.next.next = head // the node after head now points back to head
      head.next = null // head becomes the tail
      return newHead
    }

    It's elegant, but each call waits on the stack until the end of the list, so it uses O(n) memory. For long lists, the loop version is safer.

    Reference solution

    js
    /**
     * @param {ListNode | null} head
     * @return {ListNode | null}
     */
    export default function reverseList(head) {
      let prev = null // the reversed part so far (the old head will point to null)
      let current = head // the node we're flipping now
      while (current) {
        // Bookmark the rest of the list BEFORE we overwrite current.next.
        const next = current.next
        current.next = prev // flip the arrow to point backward
        // Step forward.
        prev = current
        current = next
      }
      // current is null now; prev is the old last node, i.e. the new head.
      return prev
    }
    ts
    export default function reverseList(head: ListNode | null): ListNode | null {
      let prev: ListNode | null = null // the reversed part so far (the old head will point to null)
      let current = head // the node we're flipping now
      while (current) {
        // Bookmark the rest of the list BEFORE we overwrite current.next.
        const next: ListNode | null = current.next
        current.next = prev // flip the arrow to point backward
        // Step forward.
        prev = current
        current = next
      }
      // current is null now; prev is the old last node, i.e. the new head.
      return prev
    }
    python
    def reverse_list(head: ListNode | None) -> ListNode | None:
        prev = None  # the reversed part so far (the old head will point to None)
        current = head  # the node we're flipping now
        while current:
            # Bookmark the rest of the list BEFORE we overwrite current.next.
            next_node = current.next
            current.next = prev  # flip the arrow to point backward
            # Step forward.
            prev = current
            current = next_node
        # current is None now; prev is the old last node, i.e. the new head.
        return prev