Search for a command to run...
Initialization
Both pointers start at the head.
Fast and Slow Pointers
1function removeNthFromEnd(head, n) {2 let fastp = head;//n: 3length: 53 let slowp = head;4 5 // Open a gap of exactly n6 for (let i = 0; i < n; i++) {7 fastp = fastp.next;8 }9 10 // The gap swallowed the list — the head is the target11 if (fastp === null) {12 return head.next;13 }14 15 // Move together until fast is on the last node16 while (fastp.next !== null) {17 fastp = fastp.next;18 slowp = slowp.next;19 }20 21 // slow is one before the target22 slowp.next = slowp.next.next;23 return head;24}