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.