Remove Nth Node From End of List https://leetcode.com/problems/remove-nth-node-from-end-of-list/
Fast and Slow Pointer
- slow is head and fast is moved N units from head. The idea is that after we move both by 1 until fast.next is None, we will have slow pointing to the previous node that has to be deleted.
- But there is one boundary condition: If N == size of the list, then head needs to be chopped off. Test that condition.
class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ if head == None: return None n1, n2 = head, head for _ in range(n): n2 = n2.next if n2 == None: head, n1.next = n1.next, None return head while n2.next: n1, n2 = n1.next, n2.next temp = n1.next n1.next = temp.next temp.next = None return head