# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defremoveNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: count = 0 current = head while current: count += 1 current = current.next pos = count - n index = 0 current = head
if pos == 0: return head.next
while current: index += 1 if index == pos and current.nextisnotNone: current.next = current.next.next break else: current = current.next return head