π 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)