Reverse Linked List
Reverse a singly linked list in place by turning each next pointer around, using three pointers.
The problem
You get the head of a singly linked list. Reverse the list by changing the links between the nodes, and return the new head, which is the old last node. An empty list stays empty.
Input head = [9, 4, 7, 1]
Output [1, 7, 4, 9]
Every link now points the other way, so the old tail (1) is the new head.
Input head = [42]
Output [42]
A single node is already its own reverse; the loop runs once and returns it.
Key constraint: Change the links, not the values, and use O(1) extra space; the follow-up asks for a recursive version too.
How to spot the pattern
- You must flip the direction of every link in a list.
- Many harder list problems (reversing in groups, reordering, palindrome checks) use this as a building block.
The idea
Walk the list once and turn each next pointer around so it points to the node before it. The only danger is losing the rest of the list when you overwrite next, so save it first. Three pointers are enough: prev (the part that is already reversed), curr (the node being flipped) and next (the rest of the list).
Brute force: Push every node onto a stack (or copy the values into an array) and relink them from it, which needs O(n) extra space.
Step by step
- 1Set
prevto null andcurrtohead. - 2While
curris not null, savenext = curr.next. - 3Point
curr.nextback atprev, then moveprevtocurrandcurrtonext. - 4When
currbecomes null,previs the new head, so return it.
See the pattern move
The linked lists pattern on a small example. Step through it, or press play.
Code
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
curr = head
while curr:
nxt = curr.next # save the rest of the list
curr.next = prev # flip the link
prev = curr
curr = nxt
return prevComplexity
Time
O(n)
Space
O(1)
One pass over the list, with three pointers.
Watch out for
- Overwriting
curr.nextbefore saving it, which cuts off the rest of the list. - Returning
headinstead ofprev: after the loop the old head is the tail, and itsnextis null. - In the recursive version, forgetting
head.next = null, which leaves a two-node cycle at the end.
Follow-up questions
Can you do it recursively?
Reverse the rest of the list starting at head.next, then set head.next.next = head and head.next = null, and return the new head from the recursive call. It is short, but the call stack uses O(n) space.
How would you reverse only the part between positions left and right?
Walk to the node just before position left, reverse the next right - left + 1 nodes with the same three pointers, then reconnect both ends of the reversed part. That is Reverse Linked List II.
In Hinglish
Har node ka next ulta karo, lekin pehle aage wala node save kar lo. Teen pointer chahiye: prev, curr aur next, bas.