Given a linked list, remove the n-th node from the end of list and return its head.
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Given n will always be valid.
Could you do this in one pass?
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
if (!head) return head;
let prev = head;
let curr = head.next;
while (curr) {
if (n > 0) {
n -= 1;
} else {
prev = prev.next;
}
curr = curr.next;
}
if (n === 1) return head.next;
prev.next = prev.next.next || null;
return head;
};