Python solution sharing with explanation

  • 1
    def removeNthFromEnd(self, head, n):
        keep a window with n elements from the beginning
             other n-1 elements
        [head, ...]
        maintain the window, updating the head of window, 
        Starting with the n+1 node to the end
        then after the list travel to the end, the head of window would be deleted
        (So I also need to track the node before window head "wHead")
        And if there is no "n+1" node, 
        this means "head" is what we are going to deleted
        so I just return
        if not head or not n:
            return head
        wHead = wTail = head
        for i in range(n-1):
            wTail =
        pre, cur = None,
        if not cur:
        while cur:
            pre, wHead, wTail, cur = wHead,, cur, =
        return head

Log in to reply

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