DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on • Edited on

Delete Nth Node From Last LinkedList

Approach 1:

var removeNthFromEnd = function(head, n) {
    let length = 0;
    let current = head;

    while(current){
        current = current.next;
        length++;
    };

    let reachTill = length - n;

    current = head;
    let previous=head;
    length = 0;

    if(reachTill === 0) return head.next;

   while (current) {
       if(length === reachTill){
           break;
       }
       length++
    previous = current;
    current = current.next;
   }

    previous.next = current.next;
    return head;
};
Enter fullscreen mode Exit fullscreen mode

Approach 2 :
fast & slow Pointer Explanation

var removeNthFromEnd = function(head, n) {
   let fast= head;
   let slow = head;


    for(let i=0; i< n; i++){
        fast=fast.next;
    }

    console.log(fast)

  if (!fast) return head.next;

  while (fast.next) {
    fast = fast.next;
    slow = slow.next;
  }

  slow.next = slow.next.next;
  return head;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)