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.