“This is the 22nd day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

[B] [C] [D]

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

Advanced: Can you try using a scan implementation?

(1) delete node (n); delete node (n);

  1. If the list has only one node, thennMust be equal to1, then the list after deleting the penultimate node will be empty, so if the list has only one node, it will return directlynullCan be
  2. Create a virtual head node. The node to be deleted may be a head node. Therefore, creating a virtual head node facilitates operations and simplifies processing logic
  3. Define three PointersprePoint to the virtual head,target,nextPoint to thehead
  4. willnextThe needle goes backwardsn
  5. pre,target,nextWalk backwards together untilnextPoint to thenullAt this time,targetPoint to the penultimatenA node
  6. willprePointers to elements (i.etargetOf the previous element)nextPointer totarget.nextTo delete it from the listtargetPurpose of node
  7. Return to the next node of the virtual head node

The overall process is as follows:

The code is as follows:

Var removeNthFromEnd = function(head, n) { If (head.next === null) return null; Const vhead = new ListNode(0); vhead.next = head; // define three Pointers: let pre = vhead, target = head, next = head; While (n){n--; next = next.next; } // While (next){pre = pre.next; target = target.next; next = next.next; } // Delete target pre-next from the list by pointing pre.next to target.next; return vhead.next; };Copy the code

At this point we are done with Leetcode-19 – deleting the NTH node from the list

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