The topic of dry

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

Tip:

The number of nodes in the linked list is zero

1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
Copy the code

Solution: Iteration

First of all, we need to calculate the length of the linked list, and then we need to calculate the number of nodes to delete, and then judge the number of nodes in the traverse, and delete the operation if it is consistent. One of the things to notice is that we need to do special processing on the first element. See the following code for details:

Execution time: 76 ms, beating 97.09% of all JavaScript commits

Memory consumption: 39.2 MB, beating 43.19% of all JavaScript commits

var removeNthFromEnd = function (head, n) {
    let addnum = 0;
    let workNum = head;
    while(workNum ! =null) {
        addnum++
        workNum = workNum.next;
    }
    // get the subscript we need to delete
    let targetIndex = addnum - n + 1;
    console.log(targetIndex)
    // Then we will delete three cases, respectively at the beginning of the middle is (do not worry about the end, because n is not 0)
    let prev = null;
    let current = head;
    let next = head.next;
    let currentIndex = 1;
    /* Handle deleting the first node */

    /* Handle intermediate node deletion */
    while(current ! =null) {
        if (targetIndex == 1) {
            if (next == null) {
                return null
            }
            head = next;
            current = head;
            next = current.next;
            return head
        } else {
            if (currentIndex == targetIndex) {
                prev.next = next
                return head
            } else{ prev = current; current = current.next; next = current.next; currentIndex++; }}}};Copy the code