Answers for "Remove Nth Node From End of List"

1

Remove Nth Node From End of List

var removeNthFromEnd = function(head, n) {
  if(!head.next) return null;
  
  let prev = head;
  let toDeleted = head;
  let it = head;
  let count = 1;
  
  while(it.next){
    it = it.next;
    if(count >= n){
      prev = toDeleted;
      toDeleted = prev.next;
    }
    count++;
    
  }
  
  if(prev.next === toDeleted.next){
    head = head.next;
    return head;
  }
  
  prev.next = toDeleted.next
  return head;
};
Posted by: Guest on October-16-2021
0

remove nth node from end of list

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        
        ListNode slow = head, fast = head;
        int count = 0;
        while(fast != null && fast.next != null){
            fast = fast.next;
            if(count >= n)
                slow = slow.next;
            count++;
        }
        
        if(count+1 == n) return slow.next;
        
        slow.next = slow.next.next;
        return head;
    }
}
Posted by: Guest on April-23-2021

Code answers related to "Remove Nth Node From End of List"

Code answers related to "Javascript"

Browse Popular Code Answers by Language