My accepted recursive Python solution

  • 0

    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 = 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(, n)+1
                if index == n:
                return index
            index = remove(head, n)
            if n > index:
                head =
            return head

Log in to reply

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