Skip to content
mlmentorship

Reverse Linked List

Reverse all links in a singly linked list.

Published · 3 min read ·Core ·Intermediate

30-second answer map

Visual first · depth when needed

Preserve the unreversed suffix before redirecting each current.next, then advance the previous/current boundary one node.

Preparing the visual…

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

How practice works

ML breadth · closed-book attempt

Reverse Linked List

Explain the mechanism, why it works, when it fails, and one alternative.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

Reverse all links in a singly linked list.

Start with the concrete trace below. It shows the state the algorithm must carry as it runs.

Problem trace

Reverse Linked List: Preserve the unreversed suffix before redirecting each current.next, then advance the previous/current boundary one node.

Input and goalReverse all links in a singly linked list.
Initialize the two list regionsFor 1->2->3->4->null, previous = null and head/current = 1. The whole list is still the unreversed suffix.
1current234
previousnullactualLinks1->2, 2->3, 3->4, 4->null

Recognize it
Use it when a forward-only chain must reverse direction in constant extra space and changing current.next would otherwise destroy access to the unprocessed suffix.
Keep true
Before each iteration, previous heads a fully reversed prefix, head heads the untouched forward suffix, and together those disjoint regions contain every original node exactly once.
Reuse it
Before mutating the only route to remaining work, save that route; then rewire and advance the boundary. This applies to list splicing, segment reversal, and in-place pointer transformations.
Read it this way: For 1->2->3->4->null, previous = null and head/current = 1. The whole list is still the unreversed suffix. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.

Pattern: Previous, current, and next pointers.

Simple idea: Save the next node. Point the current node backward. Move both working pointers forward.

def reverse_list(head: ListNode | None) -> ListNode | None:
   previous = None

   while head:
      next_node = head.next
      head.next = previous
      previous = head
      head = next_node

   return previous

Cost: time and space.

The platform supplies ListNode with val and next; this snippet assumes that definition.