š Reverse a Linked List ā Python (Step-by-Step)
Hi All,
Today I solved a fundamental problem in Data Structures: Reverse a Linked List.
š Problem Statement
Given the head of a singly linked list, reverse the list and return the new head.
š Example
Input:
1 -> 2 -> 3 -> 4 -> 5
Output:
5 -> 4 -> 3 -> 2 -> 1
š” Approach
š¹ Iterative Method (Optimal)
š We reverse the links one by one using pointers.
š§ Step-by-Step Logic
We use three pointers:
-
prevā previous node -
currā current node -
next_nodeā next node
Steps:
-
Initialize:
prev = Nonecurr = head
-
Traverse the list:
- Store next node
- Reverse link
- Move pointers forward
š» Python Code
class ListNode:
def __init__(self, val=0):
self.val = val
self.next = None
def reverseList(head):
prev = None
curr = head
while curr:
next_node = curr.next # store next
curr.next = prev # reverse link
prev = curr # move prev
curr = next_node # move curr
return prev
š Dry Run
For:
1 -> 2 -> 3
Steps:
- Reverse 1 ā None
- Reverse 2 ā 1
- Reverse 3 ā 2 ā 1
Final:
3 -> 2 -> 1
š„ļø Sample Output
Input: 1 -> 2 -> 3 -> 4 -> 5
Output: 5 -> 4 -> 3 -> 2 -> 1
ā” Complexity Analysis
- Time Complexity: O(n) ā
- Space Complexity: O(1) ā
š§ Alternative Method (Recursive)
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
š§ Why this is important?
- Core linked list concept
- Tests pointer manipulation
- Frequently asked in interviews
ā Conclusion
This problem helped me understand:
- Pointer handling
- Linked list traversal
- In-place reversal
š Must-know problem for coding interviews!
Top comments (0)