Linked ListEasyPointers
Reverse Linked List Visualizer
Three pointers: prev, curr, next. Flip curr.next to prev, then slide all three forward.
In easy words
Each node stops pointing right and starts pointing left. The old head becomes the tail.
Where this shows up
Undo a playlist, reverse a path, and as a building block for palindrome-list and k-group reverse.
Key facts
- prev starts None - so the old head's next becomes None (new tail).
- Save next first - otherwise you lose the rest of the list.
- Flip - curr.next = prev.
- Advance - prev = curr, curr = next.
What to remember
- Time - O(n), one pass.
- Space - O(1) iterative.
- Empty / one node - already reversed.
- Return prev - that is the new head.
Theory
Iterative reversal uses constant extra memory. Recursive reversal is cleaner to write but uses O(n) call-stack space.
Problem Statement
Reverse a singly linked list and return the new head.
Example: 1 → 2 → 3 → 4 → None becomes 4 → 3 → 2 → 1 → None.
Approach
- Three pointers: prev starts as None, curr at head.
- Save next first — nxt = curr.next — or you lose the rest of the list.
- Flip curr.next = prev, then slide prev = curr, curr = nxt.
- Stop when curr is None. prev is the new head. Time O(n), extra space O(1).
Visualization and algorithm execution
Ready
1prev = None
2curr = head
3while curr:
4nxt = curr.next
5curr.next = prev
6prev = curr
7curr = nxt
8return prev
Trace log
list (arrows show next)
Output:
Example program
1def reverseList(head):
2prev = None
3curr = head
4while curr:
5nxt = curr.next
6curr.next = prev
7prev = curr
8curr = nxt
9return prev
1struct Node { int val; struct Node *next; };
2struct Node *reverseList(struct Node *head) {
3struct Node *prev = NULL, *curr = head, *nxt;
4while (curr) {
5nxt = curr->next;
6curr->next = prev;
7prev = curr;
8curr = nxt;
9}
10return prev;
11}