Python 50ms recursive solution (btw how can it be optimazed?)


  • 0
    Q
    def removeNthFromEnd(self, head, n):
        self._current = None
    
        def probe(head, n):
            if head.next:
                order = probe(head.next, n) + 1
                if order == n:
                    self._current = head
                return order
            else:
                return 0
    
        if head:
            m = probe(head, n)
    
            if self._current:
                #del node
                temp = self._current.next
                if temp:
                    self._current.next = self._current.next.next
                    temp.next = None
            elif m < n:
                temp = head
                head = head.next
                temp.next = None
            else:
                return None
    
            return head

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.