Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 206 · Reversal

Reverse Linked List

LeetCode 206 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

prev ← temp ← front, one arrow at a time.

సులభంLinked ListRecursion
LeetCode లో తెరవండి ↗

నేను 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. 1

    prev = None, temp = head.

  2. 2

    front = temp.next; temp.next = prev.

  3. 3

    prev = temp; temp = front.

  4. 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.