InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Reverse Linked List

easy Original ↗ 00:00

Problem

Given the head of a singly linked list, reverse the direction of every next pointer and return the new head (the node that was previously the tail).

Examples

  • Input: 1 -> 2 -> 3 -> 4 -> 5 → Output: 5 -> 4 -> 3 -> 2 -> 1 Every link 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) An empty list reverses to an empty list.

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 Walking the list and flipping each next pointer in place fails: the moment you reassign node.next, you lose the reference to the rest of the list. What do you need to save before overwriting the pointer?
Hint 2 Track two pointers: prev (the already-reversed portion) and curr (the not-yet-reversed portion). Each step, point curr.next back at prev, but first save the old curr.next so you can keep advancing.
Hint 3 Recursively: reverse everything after the head first, which returns the new head. Then head.next is the tail of that reversed sublist, so attach head behind it with head.next.next = head and set head.next = None.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug