Reverse Linked List
Difficulty: Easy · Pattern: Linked List · LeetCode #206
Given the head of a singly linked list, reverse the list and return the new head.
Examples
text
1 → 2 → 3 → 4 → 4 → 3 → 2 → 1
7 → 9 → 9 → 7
(empty) → (empty)Hints
- Walk the list once, turning each
nextpointer around to point at the previous node. - Save
curr.nextbefore you overwrite it. - Recursive version: reverse the rest, then make
head.next.next = head.
Approach
Iterate with prev = None and curr = head. For each node: save nxt = curr.next, point curr.next back to prev, then advance prev = curr and curr = nxt. When curr is None, prev is the new head. The recursive solution is elegant but uses O(n) stack space.
Complexity
Time: O(n). Space: O(1) iterative.
Python solution
def reverseList(head):
prev, curr = None, head
while curr:
nxt = curr.next
curr.next = prev
prev, curr = curr, nxt
return prevJavaScript solution
function reverseList(head) {
let prev = null, curr = head;
while (curr) {
const nxt = curr.next;
curr.next = prev;
prev = curr;
curr = nxt;
}
return prev;
}