【发布时间】:2021-08-22 06:27:50
【问题描述】:
我正在尝试测试以下链表函数:
function ListNode(x) {
this.value = x;
this.next = null;
}
function removeKFromList(l, k) {
// create node
let node = new ListNode();
// assign node.next to the beginning of the given linked list.
node.next = l;
// start iterating through the linked list
let current = node;
// while there is still a node
while(current.next) {
// if the value of the node equals to given K
if (current.next.value === k) {
// remove it from the list by hopping from the one node to the next node
current.next = current.next.next
} else {
// move from one node to the next.
current = current.next;
}
}
//return the linked list
return node.next;
}
console.log(removeKFromList([3, 1, 2, 3, 4, 5], 3));
我希望输出是:[1, 2, 4, 5] 但是,输出是:[ 3, 1, 2, 3, 4, 5 ]
附言我想指出我不擅长与链接列表相关的问题,因此,如果我遗漏了一些“明显”的东西,请不要怪我。
【问题讨论】:
-
使用调试器单步调试您的代码。
-
@tgdavies,能否请您更具体一点,至于我究竟应该经历哪一部分?
标签: javascript data-structures linked-list