19. Remove Nth Node From End of List
Problem
Tags: Linked List
, Two Pointers
Given the head
of a linked list, remove the n^th
node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 1
Output: [1]
Constraints:
- The number of nodes in the list is
sz
. 1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
Follow up: Could you do this in one pass?
Code
JS
// 19. Remove Nth Node From End of List (6/17/53723)
// Runtime: 106 ms (13.41%) Memory: 40.22 MB (94.66%)
/**
* 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}
*/
function removeNthFromEnd(head, n) {
let hair = new ListNode(0, head);
let candidate_prev = hair, tail = head;
for(let i = 1; i < n; i++) tail = tail.next;
while(tail.next) {
tail = tail.next;
candidate_prev = candidate_prev.next;
}
candidate_prev.next = candidate_prev.next.next;
return hair.next;
};