InterviewPrepKit

Home / Coding / Linked List

Reverse Linked List

easy Original ↗
Solving tips
  • The core discipline: save the pointer you're about to overwrite (nxt = curr.next) before flipping curr.next = prev.
  • Walk with three pointers prev/curr/nxt; when curr becomes None, prev is the new head, so return prev (not curr).
  • For the recursive version, remember head.next.next = head then head.next = None, and return the unchanged new head from the base case.
  • Target O(n) time, O(1) space iteratively; recursion is O(n) stack and risks the recursion limit near 5000 nodes.

Problem

Given the head of a singly linked list, reverse the direction of every next pointer so the list reads back-to-front, and return the new head (the node that used to be the tail).

Examples

  • Input: 1 -> 2 -> 3 -> 4 -> 5 → Output: 5 -> 4 -> 3 -> 2 -> 1 Every link now points the other way; the old tail 5 is the new head.
  • Input: 1 -> 2 → Output: 2 -> 1 Smallest non-trivial case.
  • Input: (empty) → Output: (empty) Reversing nothing is nothing.

Constraints

  • Number of nodes is in [0, 5000].
  • -5000 <= Node.val <= 5000
  • Follow-up: solve it both iteratively and recursively.

Think about it first

Hint 1 You can't just walk the list and flip each next pointer naively — the moment you redirect node.next, you lose your only route to the rest of the list. What do you need to save first?
Hint 2 Keep two travelers: prev (the already-reversed part) and curr (the not-yet-reversed part). Each step, point curr.next back at prev — after stashing the old curr.next so you can keep walking.
Hint 3 Recursively: reverse everything after the head first, which returns the new head. Then head.next is the tail of that reversed sublist — hook head on behind it with head.next.next = head and null out head.next.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.