Remove Nth node from end of the list

View on Leetcode

Medium

Given the 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]

const removeNthFromEnd = function (head, n) { if (!head) return head; let lead = head; let follow = head; // if n > len(linked list), this will fail. // Always check if n can be greater than the len. // If yes, add the check before this condition. for (let i = 0; i < n; i++) { lead = lead.next; } // This is important for a case when n == len(linked list) // 1 -> 2 -> null, n = 2 // // i = 0; i < n; i++ // // cur // 1 -> 2 -> null, beginning of loop // // cur // 1 -> 2 -> null, after i = 0 cycle runs // // cur // 1 -> 2 -> null, after i = 1 cycle runs // // In this case when n == len(linked list), we basically // want to remove the first element of the list. // so your head becomes head.next if (!lead) { return head.next; } while (lead.next) { follow = follow.next; lead = lead.next; } follow.next = follow.next.next; return head; };