Delete the nth node in a Linked List.

Sneha Michelle,Linked Lists

Problem Link

Delete the nth node (opens in a new tab)

Problem Statement

Remember, n is counted from the last node!


Algorithm

Here, we follow the slow/fast pointer approach.

slow.next = slow.next.next ..and we return our head

Code

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
       ListNode start = new ListNode();
       start.next = head;
       ListNode fast = start; 
       ListNode slow = start;
 
       for (int i=1;i<=n;i++){
           fast = fast.next;
       }
 
       while (fast.next!=null){
           fast = fast.next;
           slow = slow.next;
       }
 
       slow.next = slow.next.next;
 
       return start.next;
    }
}