#206
Reverse Linked List
EasyLinked ListRecursionTwo PointersIn-Place Reversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution reverses the linked list in place using a three-pointer technique. This is efficient as it only requires a single pass through the list and uses constant space.
⚙️
Algorithm
3 steps- 1Step 1: Initialize three pointers: prev as null, current as head, and next as null.
- 2Step 2: Iterate through the list, and for each node, store the next node, reverse the current node's pointer to point to prev, then move prev and current one step forward.
- 3Step 3: Once the end of the list is reached, return prev as the new head of the reversed list.
solution.py15 lines
1# Full working Python code
2class ListNode:
3 def __init__(self, val=0, next=None):
4 self.val = val
5 self.next = next
6
7def reverseList(head):
8 prev = None
9 current = head
10 while current:
11 next_node = current.next
12 current.next = prev
13 prev = current
14 current = next_node
15 return prevℹ
Complexity note: This approach runs in linear time because we traverse the list once, and it uses constant space since we only use a few pointers.
- 1Reversing a linked list can be done in place, which is more efficient than creating a new list.
- 2Understanding pointer manipulation is crucial for linked list problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.