19. Remove Nth Node From End of List

Two pointers: keep first pointer n steps ahead of the second one

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // keep rightP n setps ahead of leftP
        ListNode rightP = head;
        ListNode leftP = head;
        for(int i=0; i<n; i++){
            rightP=rightP.next;
        }
        
        // if rightP is null, it means to remove the head;
        if(rightP==null){
            return head.next;
        }
        
        while(rightP.next!=null){
            leftP=leftP.next;
            rightP=rightP.next;
        }
        leftP.next=leftP.next.next;
        return head;
    }
}

Last updated