My accepted recursive Python solution


  • 0
    X

    Basically, I mark each node from the end of the list with indices starting from 0. If the index of one node is equal to n, I know its next node is the node I need to remove. Special case: if n == the length of the linked list, namely, we are asked to remove the head node, make head = head.next. Below is the code in Python.

    class Solution:
        # @return a ListNode
        def removeNthFromEnd(self, head, n):
            def remove(ptr, n):
                if ptr == None:
                    return -1
                index = remove(ptr.next, n)+1
                if index == n:
                    ptr.next = ptr.next.next
                return index
                
            index = remove(head, n)
            if n > index:
                head = head.next
            return head

Log in to reply
 

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