Remove Nth Node From End of List
Description
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
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.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
Solution(javascript)
// 直觉上会想到利用链表的长度,事实上我们并不需要知道链表的长度
const removeNthFromEnd = (head, n) => {
let h1 = head
let h2 = null
let count = 0
while (h1) {
count += 1
h1 = h1.next
if (h2) {
h2 = h2.next
}
if (count === n + 1) {
h2 = head
}
}
if (!h2) {
return head ? head.next : null
}
h2.next = h2.next.next
return head
}