Remove Nth Node From End of List
Description
Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
Example 1:
![](https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg)
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?
Solution(javascript)
/**
* 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) {
// move currentNode n steps into list
let currentNode = head;
for ( let i = 0; i < n; i++) {
currentNode = currentNode.next;
}
if (currentNode == null) {
return head.next;
}
// move both pointers until currentNode reaches the end of list
let nodeBeforeRemoved = head;
while(currentNode.next !== null) {
currentNode = currentNode.next;
nodeBeforeRemoved = nodeBeforeRemoved.next;
}
nodeBeforeRemoved.next = nodeBeforeRemoved.next.next;
return head;
// Time = O(n)
// Space = O(n)
// let length = 0;
// let currentNode = head;
// // find length of list
// while(currentNode !== null) {
// currentNode = currentNode.next;
// length++;
// }
// if (length == n) {
// return head.next;
// }
// // find the node to remove
// let nodeIndex = length - n
// let nodeBeforeRemovedIndex = nodeIndex - 1;
// currentNode = head;
// for(let i = 0; i < nodeBeforeRemovedIndex; i++) {
// currentNode = currentNode.next;
// }
// currentNode.next = currentNode.next.next;
// return head;
// // Time = O(n)
// // Space = O(1)
};