ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null) {
return null;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy; // one before the node get deleted
ListNode fast = head;
// move fast n step earlier than slow
while (n > 0) {
fast = fast.next;
n--;
}
// move them together, while fast == null, slow will be on the nth node
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}