Remove the Nth Node From the End
Problem
Given the head of a list and an integer n, remove the nth node counted from the end and return the new head. To do it in one pass, anchor a dummy before head, advance a fast pointer n + 1 steps from the dummy, then walk slow and fast together until fast falls off the end. slow now sits just before the target node, so slow.next = slow.next.next unlinks it.
Input
1→2→3→4→5, n = 2Output
1→2→3→5The 2nd-to-last node (4) is unlinked.
def remove_nth_from_end(head, n):
dummy = ListNode(0, head)
fast = slow = dummy
for _ in range(n + 1):
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
function removeNthFromEnd(head, n) {
const dummy = { val: 0, next: head };
let fast = dummy, slow = dummy;
for (let i = 0; i <= n; i++) fast = fast.next;
while (fast) { fast = fast.next; slow = slow.next; }
slow.next = slow.next.next;
return dummy.next;
}
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode fast = dummy, slow = dummy;
for (int i = 0; i <= n; i++) fast = fast.next;
while (fast != null) { fast = fast.next; slow = slow.next; }
slow.next = slow.next.next;
return dummy.next;
}
}
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode dummy(0, head);
ListNode *fast = &dummy, *slow = &dummy;
for (int i = 0; i <= n; ++i) fast = fast->next;
while (fast) { fast = fast->next; slow = slow->next; }
slow->next = slow->next->next;
return dummy.next;
}