Skip to the solution
EasyDSA14 min read

How do you reverse a linked list?

1.2k views

The problem

Question presented to candidate: "Given the head of a singly linked list, reverse it and return the new head. Write it in Python, and tell me how much extra memory it uses."

What a strong answer should cover:

  • The idea: walk the list once and point every node's next at the node before it, so the old tail becomes the head.
  • Three pointers (prev, curr, next) and why the next node must be saved before the arrow is flipped.
  • O(n) time and O(1) extra space for the iterative version; the recursive version is O(n) time but O(n) call-stack space.
  • Edge cases: empty list, one node, two nodes, and returning the new head rather than the old one.
  • Python specifics: a small ListNode class, is None checks, why the order of a one-line tuple assignment matters, and why recursion fails past CPython's default limit of about 1,000 frames.

Clarifying questions expected:

  • "Singly or doubly linked, and may I change the nodes in place or must I build a new list?"
  • "How long can the list be? That decides whether recursion is safe."

Code / implementation expected: Yes โ€” a Python reverse_list(head) with prev / curr / nxt, ideally plus the recursive version and its stack cost.

  • linked-list

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read ยท 13 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonIterative reversal with three pointers
PythonRecursive reversal and the call depth it needs

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 1 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

What is the prefix sum technique?

Continue