Coding Interview PatternsReverse Linked List
EasyIn-Place Manipulation of a Linked List
Reverse Linked List
Explanation & Solution
Description
Given the head of a singly linked list, reverse the list, and return the reversed list.
Input:head = [1,2,3,4,5]
0
1
1
2
2
3
3
4
4
5
Output:[5,4,3,2,1]
0
5
1
4
2
3
3
2
4
1
Explanation: The list 1→2→3→4→5 becomes 5→4→3→2→1.
Constraints
- The number of nodes in the list is in the range
[0, 5000] -5000 <= Node.val <= 5000
Approach
In-Place Manipulation of a Linked List pattern
1. Initialize Two Pointers
- Set
prev = null— this will become the new tail (end of the reversed list). - Set
curr = head— start processing from the head of the original list.
2. Iterate Through the List
- While
curris not null: - Save
next = curr.nextso we don't lose the rest of the list. - Reverse the pointer:
curr.next = prev. - Advance
prevtocurr. - Advance
currtonext.
3. Return the New Head
- When the loop ends,
curris null andprevpoints to the last node we visited — which is the new head of the reversed list. - Collect values into an array and return.
🧠 Key Insight
- Each iteration reverses exactly one pointer, so we process every node exactly once.
Time
O(n)single pass through the list.Space
O(1)only three pointer variables (`prev`, `curr`, `next`) are used.Visualization
Input:
Linked List Traversal
—
Press play to start traversal
Slow (S)Fast (F)Both
7 steps