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.


 


Example 1:



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

Output: [1,2,3,5]

Example 2:


Input: head = [1], n = 1

Output: []

Example 3:


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

 


Follow up: Could you do this in one pass?


🔷 Step-by-Step Logic:

  1. First traverse the list once to count total nodes.

  2. Then calculate the position to delete from the start: pos = total - n

  3. Traverse again up to that pos.

  4. Use two pointers: prev and current.

  5. When pos == 0, skip the node by: prev.next = current.next;


/**
 * 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) {
    int count = 0;
    ListNode temp = head;

    // 1. Count total nodes
    while (temp != null) {
        count++;
        temp = temp.next;
    }

    // 2. If we need to remove the head node
    if (count == n) {
        return head.next;
    }

    // 3. Move to (count - n)th node
    int pos = count - n;
    ListNode prev = null;
    ListNode current = head;

    while (pos > 0) {
        prev = current;
        current = current.next;
        pos--;
    }

    // 4. Remove the target node
    prev.next = current.next;

    return head;
}

}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence