⚡ TL;DR
Solve Reverse Linked List in Python with working code. Iterative (Optimal) approach with O(n) time, plus complexity analysis and interview tips.
Reverse Linked List (#206 — Easy): Given the head of a singly linked list, reverse the list, and return the reversed list.
Problem Statement
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]Approach: Iterative (Optimal)
Time: O(n) | Space: O(1)
Three pointers dance: save next, flip current’s pointer backward, advance both. The head becomes the tail and prev ends up as the new head.
def reverse_list(head):
prev = None
curr = head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prevApproach: Recursive
Time: O(n) | Space: O(n) (call stack)
Recursively reverse the rest of the list, then fix the current node. Elegant but uses stack space proportional to list length.
def reverse_list_recursive(head):
if not head or not head.next:
return head
new_head = reverse_list_recursive(head.next)
head.next.next = head
head.next = None
return new_headKey Takeaways
- Start with the brute-force approach to understand the problem
- Iterative (Optimal) gives the optimal O(n) solution
- Practice this pattern — it appears frequently in coding interviews
Related Problems
- Reverse Linked List in Dart
- Reverse Linked List in Go
- Reverse Linked List in Swift
- Linked List Cycle in Python
FAQ
What is the best approach to solve Reverse Linked List in Python?
The recommended approach is Iterative (Optimal), which runs in O(n) time with O(1) space. The full Python implementation is shown above.
What is the time complexity of Reverse Linked List in Python?
Using Iterative (Optimal), the time complexity is O(n) and the space complexity is O(1).
Happy coding!
