19. Remove Nth Node From End of List
Problem:
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.Solution:
Last updated
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.Last updated
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
let removeNthFromEnd = function (head, n) {
let p1 = head;
while (p1 && n--) {
p1 = p1.next;
}
if (!p1) {
return n ? head : head.next;
}
let p2 = head;
while (p1.next) {
p1 = p1.next;
p2 = p2.next;
}
p2.next = p2.next.next;
return head;
};