# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: if not head.next: # Single node input meaning n = 1 return None print(f"Nth node: {n}") col = [] idx = 0 node = head while node: if len(col) == n + 1: col = col[1:] col += [node] node = node.next s = len(col) if n > 1 and n < s: col[0].next = col[2] # Normal case elif n == 1: col[-2].next = None # Drop last elif n == s: head = col[1] # Drop first return head