Reverse Linked List

25 min · reverseList()

A chain can face the other way without changing a single value. You only need to turn each link around.

A singly linked list is a chain of nodes where each node stores a value and a link to the next node. Given the first node, reverse the whole chain and return its new first node.

A few ground rules:

  • The old tail becomes the new head, and the old head becomes the new tail.
  • Every value must appear exactly as often as it did before.
  • An empty list stays empty.

Constraints

  • 0 <= list length <= 10_000
  • -1_000_000_000 <= Node.val <= 1_000_000_000

Hints

Protect the road ahead

If you redirect current.next immediately, you lose the rest of the list. Save that next node somewhere before changing the link.

Carry the reversed prefix

Keep previous as the head of the part you've already reversed. Point current.next at previous, then move both names one node forward.

Know what to return

When current finally becomes null, previous is sitting on the old tail — exactly the new head you need.

Follow-up

Can you write a recursive version too, then explain why its call stack uses O(n) space even though the pointer work looks the same?

Visible cases

Examples

Example 1

ready
Input
head = [
  1,
  2,
  3,
  4,
  5
]
Expected
[
  5,
  4,
  3,
  2,
  1
]
Why
the tail becomes the head and every link changes direction

Example 2

ready
Input
head = [
  1,
  2
]
Expected
[
  2,
  1
]
Why
two nodes swap their order

Example 3

ready
Input
head = []
Expected
[]
Why
an empty chain has nothing to reverse

Interview signal

Asked at

AmazonMicrosoftMetaApple
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite