philosyang.com

19. Remove Nth Node From End of List

Canonical idea: fast/slow pointers.

 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
 6class Solution:
 7    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
 8        # canonical idea:
 9        # fast/slow pointers - fast will be n node faster
10
11        fast = slow = head
12        for i in range(n):
13            fast = fast.next
14        
15        # special case
16        if not fast:
17            return head.next
18
19        while fast.next:
20            slow = slow.next
21            fast = fast.next
22        
23        prev = slow
24        prev.next = slow.next.next
25
26        return head

#Neetcode150 #Linked-List #Python