Reverse Linked List DSA Solution - Pointer Reversal - Study Chapter | QuizMaker
Reverse Linked List explained with brute force, optimized pointer reversal, dry run, edge cases, complexity, and Python, C++, Java code.
- Read
- 9m
- Type
- Chapter
- Access
- Free
Course
DSA Course: Interview Patterns and Problem Solving
Topic
Module 5: Linked List
Learning Outcome
After this lesson, you should be able to reverse a linked list in-place while carefully preserving the next node before changing pointers.
Problem Statement
Given the head of a singly linked list, reverse the list and return the new head.
| Input | Output | Why |
|---|---|---|
1 -> 2 -> 3 -> 4 | 4 -> 3 -> 2 -> 1 | Every pointer direction is reversed. |
Brute Force Approach
Copy all node values into an array, then rebuild a new linked list in reverse order.
This is easy to visualize, but it uses O(n) extra space and does not practice pointer manipulation.
Optimized Approach
Use three pointers: prev, curr, and nextNode. Save curr.next, point curr.next to prev, then move both pointers forward.
The key safety rule is to save the next node before changing curr.next.
Exact Pseudocode
prev = null
curr = head
while curr is not null:
nextNode = curr.next
curr.next = prev
prev = curr
curr = nextNode
return prev
Reference Code
class Solution:
def reverseList(self, head):
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr) {
ListNode* nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}
return prev;
}
};
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextNode = curr.next;
curr.next = prev;
prev = curr;
curr = nextNode;
}
return prev;
}
}
Sample Dry Run
| Step | curr | nextNode | prev after reversal |
|---|---|---|---|
| Start | 1 | - | null |
| Reverse 1 | 1 | 2 | 1 -> null |
| Reverse 2 | 2 | 3 | 2 -> 1 -> null |
| Reverse 3 | 3 | 4 | 3 -> 2 -> 1 -> null |
| Finish | null | - | Return 4 -> 3 -> 2 -> 1 |
Complexity
| Measure | Value | Reason |
|---|---|---|
| Time | O(n) | Each node is visited once. |
| Space | O(1) | The reversal is in-place. |
Edge Cases
- Empty list returns
null. - Single-node list returns the same node.
- Saving
nextNodeis required before changingcurr.next.
Interview Checklist
- Save the next node before rewiring.
- Move
prevandcurrin the right order. - Return
prev, not the old head.
FAQs
Why do we need three pointers?prev builds the reversed part, curr is the node being processed, and nextNode preserves the remaining list.
Yes, but the iterative version is usually easier to explain and uses O(1) extra space.
What is the core pattern?Pointer reversal.
Tags
- dsa
- data structures and algorithms
- linked list
- pointer reversal
- easy
- interview preparation