Difficulty: Easy-Medium | Asked at: Amazon, Apple, Adobe
Reverse a singly linked list, iteratively.
Input: 1 β 2 β 3 β 4 β None
Output: 4 β 3 β 2 β 1 β None
π‘ Hint: You need to track three pointers as you walk the list: the previous node, the current node, and the next node - because once you flip a pointer, you lose the way forward unless you saved it first.
Solution:
python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_list(head):
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
Complexity: O(n) time, O(1) space - this is the detail that separates a strong answer from an average one. A recursive solution is O(n) time but O(n) space due to the call stack - know both, and be ready to explain the tradeoff.
Common mistake: Forgetting to save
curr.next before overwriting it, which permanently disconnects the rest of the list.Iterative or recursive - which do you reach for first, and why? π