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.