Data Structures · Visualization
Linked List: Reverse
Linked List
Reversing a linked list flips the direction every 'next' pointer points in, so the old tail becomes the new head. Time: O(n). Space: O(1) iterative (O(n) if done recursively, due to call stack).
Big-O: Lookup O(n); insert/delete at head O(1).
Linked List: Reverse
Linked ListReversing a linked list flips the direction every 'next' pointer points in, so the old tail becomes the new head. This is done in a single pass by walking through the list and, at each node, redirecting its 'next' pointer to point backward instead of forward, using three tracking pointers: previous, current, and next.
How Reverse Works
- Set previous to null and current to head.
- While current is not null: save current.next in a temporary variable 'nextNode'.
- Point current.next backward to previous.
- Move previous to current, then move current to nextNode.
- When current becomes null, previous is the new head.
Reverse Worked Example
Input: head -> 1 -> 2 -> 3 -> null
- prev=null, cur=1: 1.next=null; prev=1, cur=2
- prev=1, cur=2: 2.next=1; prev=2, cur=3
- prev=2, cur=3: 3.next=2; prev=3, cur=null
- Loop ends. New head = prev = 3
Output: head -> 3 -> 2 -> 1 -> null
Press ▶ Run to watch it step by step.
def reverse(head):
prev = None
cur = head
while cur:
nxt = cur.next # save next
cur.next = prev # rewire pointer
prev = cur
cur = nxt
return prev # new head
# example: reverse on [1, 2, 3]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Reverse Time & Space Complexity
When to Use Reverse
- Reversing the order of a playlist or history stack
- A very common interview question testing pointer manipulation
- Preprocessing step for algorithms like palindrome checks on lists
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.