Reverse Linked List
EasyHow to recognize it
A singly linked list, and you need to reverse the direction of all pointers. The signal: "reverse", "flip direction", or showing output as last→...→first. This is the building block for many linked list problems.
The core idea
Maintain three pointers: prev (initially null), curr (at head), next (save curr.next before we change it). Iterate through the list, at each step reversing the pointer from curr→next to curr→prev. Move all three pointers forward one step. After the loop, prev points to the new head.
Why It's Tricky
Reversing a linked list looks simple but is deceptively easy to get wrong. The key is that you're modifying pointers while iterating, so you MUST save the next node before breaking the link. Forgetting this causes you to lose the rest of the list.
The Key Insight
The core move: `curr.next = prev` instead of `curr.next = curr.next.next`. You're flipping the pointer direction, not skipping nodes. Always save `next = curr.next` first.
Step-by-Step Walkthrough
Example: 1→2→3→null
Start: prev=null, curr=1
Step 1: next=2, 1.next=null, prev=1, curr=2
Step 2: next=3, 2.next=1, prev=2, curr=3
Step 3: next=null, 3.next=2, prev=3, curr=null
Loop ends, return prev (which is 3)
Result: 3→2→1→null
def reverseList(head):
prev, curr = None, head
while curr:
next = curr.next # Save next node
curr.next = prev # Reverse the pointer
prev, curr = curr, next # Move forward
return prevInterview gotchas
- Must save
next = curr.nextBEFORE changingcurr.next, or you lose the rest of the list. - Initial
prev = null— the old head's next should point to null. - Return
prev, NOThead— head is now the tail and points to null. - Off-by-one: Make sure your loop condition is
while curr is not null, notwhile curr.next.
💡 What to Say in the Interview
- Say: "I'll use three pointers to reverse the links in one pass."
- Explain: "At each step, I save the next node, reverse the pointer from curr to prev, then move all pointers forward."
- Emphasize: "Saving next is critical — without it, I'd lose access to the rest of the list."
- Complexity: "O(n) time (visit each node once), O(1) space (only three pointers)."