My one pass solution with two pointers

  • 7
    class Solution:
    def removeNthFromEnd(self, head, n):
    	cur = head
    	npre= head
    	dis = 0
    	count = 1
    	while is not None:
    		cur =
    		count += 1
    		dis += 1
    		while dis > n:
    			npre =
    			dis -= 1
    	if count <= n:
    		return =
    	return head

    You should pay attention to the case which removes the first node.

  • 2

    this is a very smart method........

  • 2

    Same idea but different way to handle removing head case:

    def removeNthFromEnd(self, head, n):
        slow = fast = head
        for i in range(n):
            fast =
        if fast is None:
            fast =
        while fast:
            fast =
            slow = =
        return head

  • 0

    a little bit redundant, why not make inner loop as a if statement and remove dis-=1, that straightforward

  • 0

    two pointers already mean two passes (instead of one pass as required), right?

  • 0
    while dis > n

    could be simply changed to

    if dis > n

Log in to reply

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