Skip to content
Problem 206 · LeetCode 206(opens in a new tab)

Reverse Linked List

EasyLinked lists

You are given head, the first node of a singly linked list. Each node holds a number and a link to the node after it; the last node links to nothing.

Turn the list around so the last node comes first and every link points the other way. Return the new first node. An empty list stays empty.

Example 1

Input:  head = [7, 2, 9, 4]
Output: [4, 9, 2, 7]
Why:    the last node, 4, becomes the head
2 more examples and the constraints

Example 2

Input:  head = [5, -3]
Output: [-3, 5]
Why:    two nodes simply swap places

Example 3

Input:  head = []
Output: []
Why:    there is nothing to turn around

Constraints

  • 0 ≤ number of nodes ≤ 5,000
  • −5,000 ≤ each node's value ≤ 5,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Stack of valuesO(n)
  2. RecursionO(n)
  3. Three pointers, one passO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 5,000 nodesVerdict
Stack of valuesO(n), O(n) space
Works, but dodges the real question
RecursionO(n), O(n) space
Short; mind the stack depth
Three pointers, one passO(n), O(1) space
Best; one pass, no extra memory

n = number of nodes. All three are linear; the bars reflect passes over the list and extra memory.

Edge cases to test

  • Empty list. head is null; return null without touching anything.
  • One node. [42] comes back as [42]; its next must still be null.
  • Two nodes. [5, -3] becomes [-3, 5]; check the old head now points to null, not back at -3.
  • Long list. 5,000 nodes is deep enough to break Python recursion at its default limit.

Common mistakes

  • Flipping curr.next before saving it, so the rest of the list is lost.
  • Returning curr or head at the end instead of prev; curr is null by then and head is now the tail.
  • In the recursive version, forgetting head.next = null, which leaves a two-node cycle at the end.

How to talk through it

  1. 1Clarify. Can the list be empty? May I change the links in place, or must the input stay untouched?
  2. 2Give the simple idea. Copy the values onto a stack and write them back; say it costs O(n) memory and dodges the links.
  3. 3Name the danger. Flipping a link cuts you off from the rest, so you must save next before each flip.
  4. 4Code the three pointers. Say the loop invariant: prev heads the reversed part, curr heads what is left.
  5. 5Test out loud. Run the empty list, one node and two nodes; then offer the recursive version as the follow-up.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?