remove-nth.py (1121B)
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, val=0, next=None): 4 # self.val = val 5 # self.next = next 6 class Solution: 7 def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: 8 9 ############################################# 10 11 # IDEA: 12 13 # two pointers, sliding window 14 # left_ptr = right_ptr's index - (n + 1) 15 # right_ptr increments until reaching the end 16 # once right_ptr is at the end, left_ptr is one position before the point to remove 17 # at this point, we set left_ptr's next to be left_ptr.next.next. 18 19 ############################################# 20 21 if head.next is None: 22 return None 23 24 left_node = head 25 right_node = head 26 27 for i in range(0, n): 28 right_node = right_node.next 29 30 if right_node is None: 31 return head.next 32 33 while right_node.next is not None: 34 right_node = right_node.next 35 left_node = left_node.next 36 37 left_node.next = left_node.next.next 38 return head