python - del nth node - one pass

  • 0
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    # = 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 = if l2 else head
                n -= 1
            while l2 and
                l1 = if l1 else head
                l2 =
            # delete last elt
            # delete from empty list
            if l1:
       = (
                head = 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.