One Pass Python Solution


  • 1
    R
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def removeNthFromEnd(self, head, n):
            """
            :type head: ListNode
            :type n: int
            :rtype: ListNode
            """
            faster, flag = head, True
            for i in range(0,n):
                faster = faster.next
            
            while faster:
                if flag:
                    slower, flag = head, False
                else:
                    slower = slower.next
                faster = faster.next
            
            if flag:
                head = head.next
            else:
                slower.next = None if not slower.next else slower.next.next
            
            return head
    

Log in to reply
 

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