Python with dummy node


  • 2
    class Solution(object):
        def removeNthFromEnd(self, head, n):
            if n == 0 or head is None:
                return head
            dummy = ListNode(-1)
            dummy.next = head
            fast = slow = dummy
            k = n
            while fast and k > 0:
                fast = fast.next
                k -= 1
            
            while fast and fast.next:
                fast = fast.next
                slow = slow.next
                
            if slow.next:
                slow.next = slow.next.next
                
            return dummy.next

Log in to reply
 

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