62 ms python solution with one time search


  • 0
    S
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # @return a ListNode
        def removeNthFromEnd(self, head, n):
            p1 = head # counting node
            for i in range(n-1):
                if p1.next is None:
                    return
                p1 = p1.next
            if p1.next is None:
                head = head.next
                return head
            else:
                p1 = p1.next
                p2 = head
                while p1.next is not None:
                    p1 = p1.next
                    p2 = p2.next
                p2.next = p2.next.next
                return head

Log in to reply
 

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