Easy to understand python solution, with explaination


  • 0
    Y

    Use two pointer and two pass, one to count the length of linked list, the other to go to Nth node from the end, then skip the node. Dummy head is applied to return the linked list.
    AC at 46ms

        def removeNthFromEnd(self, head, n):
            """
            :type head: ListNode
            :type n: int
            :rtype: ListNode
            """
            l1=ListNode(0)
            l2=ListNode(0)
            h1=l1
            l1.next=head
            l2.next=head
            count=-1
            while l2:
                l2=l2.next
                count+=1
            while l1 and count>n:
                l1=l1.next
                count-=1
            if l1.next:
                l1.next=l1.next.next
                return h1.next
            else:
                return []
    

Log in to reply
 

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