我是一个可以翻译文本的助手。以下是涉及 IT 技术的内容。您需要从单链表中移除值为 k 的元素,这是一道 CodeFights 问题。以下是我所拥有的代码(其中 l 表示列表,k 表示值):
CodeFight测试用例是3 -> 1 -> 2 -> 3 -> 4 -> 5。最终的结果应该是1 -> 2 -> 4 -> 5。但是我的'---'控制台日志不断返回“Empty”(根据CodeFights控制台)。每次循环时,我的'+++'控制台日志都返回正确的头元素。我一直在为此苦恼,有什么遗漏吗?
function removeKFromList(l, k) {
//figure out the head of the new list so we can reference it later
var head = l;
while (head.value === k){
head = head.next;
}
var node = head;
var temp = null;
while (node && node !== null) {
if (node.next.value === k){
temp = node.next.next;
node.next.next = null;
node.next = temp;
}
node = node.next;
console.log("+++", head)
}
console.log("---", head)
}
CodeFight测试用例是3 -> 1 -> 2 -> 3 -> 4 -> 5。最终的结果应该是1 -> 2 -> 4 -> 5。但是我的'---'控制台日志不断返回“Empty”(根据CodeFights控制台)。每次循环时,我的'+++'控制台日志都返回正确的头元素。我一直在为此苦恼,有什么遗漏吗?
while (node && node.next != null)
。 - David G