Python solution sharing with explanation


  • 1
    O
    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 head.next
        """
        if not head or not n:
            return head
        wHead = wTail = head
        for i in range(n-1):
            wTail = wTail.next
        pre, cur = None, wTail.next
        if not cur:
            return head.next
        while cur:
            pre, wHead, wTail, cur = wHead, wHead.next, cur, cur.next
        pre.next = wHead.next
        return head

Log in to reply
 

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