My Python solution in 63ms


  • 0
    C
    class Solution:
        # @return a ListNode
        def removeNthFromEnd(self, head, n):
            if head == None:
                return None
            
            p1 = p2 = head
            
            for i in range(n):
                p2 = p2.next
            
            if not p2:
                return head.next
            
            while p2 and p2.next != None:
                p2 = p2.next
                p1 = p1.next
                
            if p1.next:
                p1.next = p1.next.next
                return head
            else:
                return None

  • 0
    B

    for i in range(n): p2 = p2.next
    The above might fail when n is more than the list length.

    I guess the current OJ testcases do not test when the n is more than linkedlist's length. Can we request to add this testcase please?


  • 0
    J

    Note:
    Given n will always be valid.
    Try to do this in one pass.


  • 0
    B

    Thank you, I missed it.


Log in to reply
 

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