Reverse Linked List
LeetCode 206 · সহজ · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
prev ← temp ← front, one arrow at a time.
আমি Reverse Linked List (LeetCode 206) এভাবে সমাধান করেছি — Reversal প্যাটার্নের একটি সহজ প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
Walk the list and flip each arrow to point backwards. You need three references: the previous node (new next), the current node, and the original next (so you don't lose the rest of the list).
Approach
- 1
prev = None, temp = head.
- 2
front = temp.next; temp.next = prev.
- 3
prev = temp; temp = front.
- 4
prev is the new head.
আমি কীভাবে সমাধান করেছি
Iterative pointer flipPythonO(n) time · O(1) space
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
temp = head
prev=None
front = None
while temp:
#prev temp front
#prev temp front
front = temp.next
temp.next = prev
prev=temp
temp=front
return prev
Reverse Linked List — সাধারণ প্রশ্ন
Reverse Linked List-এর পেছনে intuition কী?
Walk the list and flip each arrow to point backwards. You need three references: the previous node (new next), the current node, and the original next (so you don't lose the rest of the list).
Reverse Linked List (LeetCode 206) কীভাবে সমাধান করবেন?
1. prev = None, temp = head. 2. front = temp.next; temp.next = prev. 3. prev = temp; temp = front. 4. prev is the new head.
Reverse Linked List-এর time আর space complexity কত?
Time: O(n)। Space: O(1)। (Accepted approach: Iterative pointer flip।)
Reverse Linked List-এ সাধারণ ভুলগুলো কী?
Save temp.next before overwriting it.