19. Remove Nth Node From End of List
Medium
Input: head = [1,2,3,4,5], n = 2
Output:
[1,2,3,5]Input: head = [1], n = 1
Output:
[]Input: head = [1,2], n = 1
Output:
[1]Last updated
Input: head = [1,2,3,4,5], n = 2
Output:
[1,2,3,5]Input: head = [1], n = 1
Output:
[]Input: head = [1,2], n = 1
Output:
[1]Last updated
# 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]:
slow, fast = head, head
for _ in range(n):
fast = fast.next
if not fast:
return slow.next
while fast.next:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return head