26 Dec 19. Remove Nth Node From End of List
Posted at 22:24h in Coding 0 Comments
head of a linked list, remove the
nth node from the end of the list and return its head.
Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]
Input: head = , n = 1 Output: 
Input: head = [1,2], n = 1 Output: 
- The number of nodes in the list is
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
Follow up: Could you do this in one pass?
# 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 = head fast = head while n > 0: fast = fast.next n = n-1 while fast is not None and fast.next is not None: fast = fast.next slow = slow.next if fast is not None: slow.next = slow.next.next else: head = head.next return head