0019 - Remove Nth Node From End of List

0019 - Remove Nth Node From End of List

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

Examples

Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]

Input: head = [1], n = 1 Output: []

Input: head = [1,2], n = 1 Output: [1]

Constraints

The number of nodes in the list is sz. 1 <= sz <= 30 0 <= Node.val <= 100 1 <= n <= sz

Java Solution

/**
 * 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) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode p1 = dummy;
        ListNode p2 = dummy;
        
        for(int i = 0; i <= n; i++) {
            p2 = p2.next;
        }
        
        while(p2 != null) {
            p1 = p1.next;
            p2 = p2.next;
        }
        
        p1.next = p1.next.next;
        return dummy.next;

    }
}

Last updated