Skip to content

Latest commit

 

History

History
58 lines (42 loc) · 957 Bytes

3.remove-nth-node-from-end-of-list.md

File metadata and controls

58 lines (42 loc) · 957 Bytes

Remove Nth Node From End of List

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

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

JavaScript
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function(head, n) {
    
      if (!head) return head;
  
  let prev = head;
  let curr = head.next;
  
  while (curr) {
    if (n > 0) {
      n -= 1;
    } else {
      prev = prev.next;
    }
    
    curr = curr.next;
  }
  
  if (n === 1) return head.next;
  
  prev.next = prev.next.next || null;
  return head;
};