LeetCode 206: Reverse Linked List — Step-by-Step Visual Trace
Watch pointers move through a linked list reversal, line by line
The Problem
Given the head of a singly linked list, reverse the list and return the reversed list.
Input: head = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
This is one of the most classic interview questions — simple enough to explain in 30 seconds, but tricky enough that getting the pointer manipulation right under pressure trips people up.
The Approach: Three Pointers
The iterative approach uses three pointers: prev, current, and next_node.
- Start with
prev = Noneandcurrent = head - At each step:
- Save the next node:
next_node = current.next - Reverse the pointer:
current.next = prev - Move forward:
prev = current,current = next_node
- Save the next node:
- When
currentisNone,prevpoints to the new head
Time: O(n) — single pass through the list Space: O(1) — only three pointer variables
The Code
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
Watch It Run
The best way to understand pointer manipulation is to see it happen. TraceLit traces your code line by line and shows you exactly how prev, current, and next_node move through the list at each step.
Try it yourself: Open TraceLit and step through the trace. You can also paste your own solution and test it with different inputs.
Key Insight
The trick is the order of operations. If you reverse current.next = prev before saving current.next, you lose the reference to the rest of the list. That's why next_node = current.next must come first.
This pattern — save, reverse, advance — shows up in many linked list problems:
- LeetCode 92: Reverse Linked List II
- LeetCode 25: Reverse Nodes in k-Group
- LeetCode 234: Palindrome Linked List
Built with TraceLit — the visual algorithm tracer for LeetCode practice.
