Example: Remove Nth node from end of list - rFronteddu/general_wiki GitHub Wiki

Given the head of a linked list, remove the nth node from the end of the list and return its head.

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // Create two pointers, first and second.
        // Move the first pointer n steps forward.
        // then, move both first and second pointers one step at a time until first reaches the end. 
        // Now, second will point to the node just before the n-th node from the end.
        // Remove the n-th node.
        var first = head;
        var second = head;
        
        while (n != 0) {
            n--;
            if(first != null) first = first.next;
        }
        if (first == null) {
            // if I reeach the end, I must update the head
            return head.next;
        }
        
        // first reaches the end when its next is null
        while (first.next != null) {
            first = first.next;
            second = second.next;
        }
        
        second.next = second.next.next;
        return head;
    }
}