Python, dummy head simplify the problem


  • 1
    Z

    Use a dummy so not to worry if n is 1 or the length of the linked list..

    def removeNthFromEnd(self, head, n):
        dummy = l = ListNode(0)
        dummy.next = r = head
        for _ in range(n):
            r = r.next
        while r:
            l, r = l.next, r.next
        l.next = l.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.