【发布时间】:2018-05-23 17:48:35
【问题描述】:
我正在解决 CodeFights 问题,试图从值为 k 的单链表中删除元素。
以下是我所拥有的(l 是列表,k 是值):
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。但是我的“---”控制台日志不断返回“空”(根据 CodeFights 控制台)。
我的“+++”控制台日志在每个循环中返回正确的头部和元素。
我一直在为此烦恼,知道这里缺少什么吗?
【问题讨论】:
-
请把list的例子也加进去,作为带值函数的调用。
-
我包含在测试用例中。该列表已作为 SLL 给出,因此我不必创建一个。希望这会有所帮助
-
一个问题是第一个节点,您需要将下一个节点指定为列表的开始。这仅适用于通过对象提供的列表。
-
你的while循环条件应该是
while (node && node.next != null)。
标签: javascript algorithm linked-list closures singly-linked-list