My easy understanding 48ms python solution


  • 2
    Y

    class Solution:

    def removeNthFromEnd(self, head, n):
        pre = head
        length = 0
        while(pre):
            length += 1
            pre = pre.next
       
        if length == n :
            return head.next
        else:
            cur = head
            for i in range(length - n-1):
                cur = cur.next
            
            cur.next = cur.next.next
            return head

  • 0
    C

    Nice solution, if you add a dummy node in the front, it will be much easier to understand:

    def removeNthFromEnd(self, head, n):
        dummy = ListNode(0)
        dummy.next = head
        front = end = dummy
        while n+1:
            front = front.next
            n -= 1
        while front:
            end = end.next
            front = front.next
        end.next = end.next.next
        return dummy.next

  • 0

    You didn't "add a dummy node". You switched to a completely different approach.

    I don't think a dummy makes your approach easier, btw. Here's yours without a dummy:

    def removeNthFromEnd(self, head, n):
        front = end = head
        while n:
            front = front.next
            n -= 1
        if not front:
            return head.next
        while front.next:
            end = end.next
            front = front.next
        end.next = end.next.next
        return head
    

  • 0
    Y

    Thank you! But my approach is different from yours.You use two pointers to find the position of the node, but I only use one pointer .


Log in to reply
 

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