Deletes the penultimate node of the linked list

Given a linked list, delete the NTH node from the bottom and return to the head of the list

The problem solving code

Use double pointer method, one pointer moves n steps backward, then both Pointers move simultaneously. Until the node that took the first N steps reaches the end of the list, then the distance between the other pointer and the last node is n.

var removeNthFromEnd = function(head, n) {
  if(! head)return null;
  let ret = new ListNode(-1,head); / / empty head
  let p = ret;
  let q = head; / / the head pointer
  while (n--) q = q.next; // Take n steps first
  while (q) { // All the way to the end of the list
    q = q.next;
    p = p.next;
  }
  p.next = p.next.next; // The next bit of the p node points to the next bit, and n is skipped. Because n = p next;
  return ret.next; // Return the list head node
};
Copy the code