Reverse Linked List
LeetCode 206 · Easy · solution, intuition & step-by-step walkthrough
prev ← temp ← front, one arrow at a time.
This is how I solved Reverse Linked List (LeetCode 206), an easy problem from the Reversal pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Walk the list and flip each arrow to point backwards. You need three references: the previous node (new next), the current node, and the original next (so you don't lose the rest of the list).
Approach
- 1
prev = None, temp = head.
- 2
front = temp.next; temp.next = prev.
- 3
prev = temp; temp = front.
- 4
prev is the new head.
How I solved it
Iterative pointer flipPythonO(n) time · O(1) space
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
temp = head
prev=None
front = None
while temp:
#prev temp front
#prev temp front
front = temp.next
temp.next = prev
prev=temp
temp=front
return prev
Reverse Linked List — FAQ
What is the intuition behind Reverse Linked List?
Walk the list and flip each arrow to point backwards. You need three references: the previous node (new next), the current node, and the original next (so you don't lose the rest of the list).
How do you solve Reverse Linked List (LeetCode 206)?
1. prev = None, temp = head. 2. front = temp.next; temp.next = prev. 3. prev = temp; temp = front. 4. prev is the new head.
What is the time and space complexity of Reverse Linked List?
Time: O(n). Space: O(1). (Accepted approach: Iterative pointer flip.)
What are common mistakes in Reverse Linked List?
Save temp.next before overwriting it.