题目要求只遍历一次,可以通过递归解决。如果我们从后面往前数,最后一位是 1 的话,那么找到的第 n 位正好符合题意是要删除的那个。
递归的过程中,函数需要两个节点,因为如果找到目标节点的时候需要重新赋值。
这个题目还有一个坑就是说如果删除头部第一个节点的时候怎么办。我们可以通过判断 n 和链表长度是否相等来处理这种边界情况。如果相等的话直接返回头部的下一个节点就行了。
const removeNthFromEnd = function(head, n) {
const traverse = (prev, curr) => {
// this is the end
if (!curr) {
return 0;
}
// accumulate the depth
const depth = traverse(curr, curr.next) + 1;
// if current node is the target
if (depth === n && !!prev) {
prev.next = curr.next;
}
// always return the depth for outer scope
return depth;
}
// handle the edge case
return traverse(null, head) === n ? head.next : head;
};