Reversing a linked list is one of the most important and commonly asked problems in data structures.
It helps you understand pointer manipulation and traversal logic.
๐ Problem Statement
Given the head of a linked list, reverse the list and return the new head.
๐ Example
Input:
1 โ 2 โ 3 โ 4 โ 5 โ NULL
Output:
5 โ 4 โ 3 โ 2 โ 1 โ NULL
๐ง Intuition
In a linked list, each node points to the next node.
๐ To reverse it, we need to:
- Change the direction of each pointer
- Make each node point to the previous node instead
๐ Approach (Iterative Method)
Step-by-Step:
- Initialize three pointers:
prev = Nonecurrent = headnext_node = None
- Traverse the list:
- Store next node
- Reverse current pointer
- Move pointers forward
๐ป Python Code
```python id="rev1"
class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(head):
prev = None
current = head
while current:
next_node = current.next # store next
current.next = prev # reverse link
prev = current # move prev
current = next_node # move current
return prev
---
๐งพ Dry Run
For: 1 โ 2 โ 3 โ NULL
Step-by-step:
* Step 1: 1 โ NULL
* Step 2: 2 โ 1 โ NULL
* Step 3: 3 โ 2 โ 1 โ NULL
Final: 3 โ 2 โ 1 โ NULL
---
โก Complexity
Time Complexity: O(n)
Space Complexity: O(1)
---
๐ฅ Why This Works
* Each node is visited once
* Links are reversed in-place
* No extra memory required
---
๐ Alternative Approach (Recursive)
```python id="rev2"
def reverseList(head):
if not head or not head.next:
return head
new_head = reverseList(head.next)
head.next.next = head
head.next = None
return new_head
โ ๏ธ Edge Cases
- Empty list โ return None
- Single node โ return same node
๐ Conclusion
Reversing a linked list is a core problem that teaches:
- Pointer manipulation
- Iterative vs recursive thinking
- In-place operations
Top comments (0)