Delete the NTH node from the linked list
Give you a linked list, remove the NTH node from the reciprocal of the list, and return the head node of the list.
Advanced: Can you try using a scan implementation?
Example 1:
Input: head = [1,2,3,4,5], n = 2Copy the code
Example 2:
Input: head = [1], n = 1Copy the code
Example 3:
Input: head = [1,2], n = 1Copy the code
Tip:
The number of nodes in the list is sz 1 <= sz <= 30 0 <= node. val <= 100 1 <= n <= szCopy the code
答 案 :
- Using a double pointer n1,n2 is set in the header
- Considering the boundary problem, when only one node is deleted, dummy node needs to be used as the head node
- The for loop iterates n2 n positions ahead of N1
- If n2 is not an empty node, N1 and n2 are moved simultaneously. If N2 is an empty node, the last node where N1 is located is the node to be deleted.
- To delete a node after n1, make the next node of N1 point to the next node of the next node of N1, n1.next = N1.next
- Finally, return head, dummy. Next
Illustration:
Code:
**
* Definition for singly-linked list.
* function ListNode(val, next) {*this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/ * * *@param {ListNode} head
* @param {number} n
* @return {ListNode}* /
var removeNthFromEnd = function(head, n) {
let dummy = new ListNode();
dummy.next = head;
let n1 = dummy;
let n2 =dummy;
for( let i = 0; i <= n; i++) {
n2 = n2.next
}
while(n2 ! = =null) {
n1 = n1.next;
n2 = n2.next;
}
n1.next = n1.next.next;
return dummy.next;
};
Copy the code