Look a hundred times beauty, beauty is not necessarily yours. But if you run the algorithm a hundred times, the knowledge is yours

Who can get up from nine floors?

Title address

The title

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

Example 1:

Input: head = [1,2,3,4,5], n = 2Copy the code

Example 2:

Input: head = [1], n = 1 output: []Copy the code

Example 3:

Input: head = [1,2], n = 1Copy the code

Tip:

  • The number of nodes in the linked list is zerosz
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

Their thinking

  • Define two Pointers. Fast Pointers are faster than slow Pointersn
  • When the fast pointer reaches the end node, the slow pointer reaches the node to be deleted
  • Deletion is accomplished by pointing the next node of the slow pointer to the node after the node to be deleted

The problem solving code

var removeNthFromEnd = function(head, n) {
    let vnode = new ListNode(-1,head)
    let slow = vnode
    let fast = vnode
    while(n--) fast =fast.next
    if(! fast)return vnode.next
    while(fast.next){
        fast=fast.next
        slow= slow.next
    }
    slow.next = slow.next.next
    return vnode.next
};
Copy the code

If you have any questions or suggestions, please leave a comment!