python - del nth node - one pass


  • 0
    S
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def removeNthFromEnd(self, head, n):
            """
            :type head: ListNode
            :type n: int
            :rtype: ListNode
            """
            l1, l2 = None, None
            
            # its good to have ref to the node prior to deleted node
            # else impossibru to del last node
            while n:
                l2 = l2.next if l2 else head
                n -= 1
            
            while l2 and l2.next:
                l1 = l1.next if l1 else head
                l2 = l2.next
            
            # delete last elt
            # delete from empty list
            if l1:
                l1.next = (l1.next).next
            else:
                head = head.next if head else None
            
            return head
    

Log in to reply
 

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