测试链表功能的问题

issue with testing Linked List's function

我正在尝试测试以下链表函数:

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 ]
P.S。我想指出,我不擅长与链表相关的问题,因此,如果我遗漏了一些“明显”的东西,请不要怪我。

你可能不知道LinkedList的含义。首先,您创建了一个 node,然后您将其 next 分配为 node.next = l。这里l是一个列表,不是节点,不能调用node.next.nextcurrent.next.next

您的 removeKfromList 函数是正确的,但它希望它的第一个参数是一个链表,并且它 returns 是对链表的引用。

但是你用一个数组调用它,并期望输出是一个数组。

我猜您对一些代码挑战站点感到困惑,这些站点从标准输入获取输入,格式化为数组,但在实际调用解决方案代码之前首先将该输入转换为链表。

为了让它在该站点的框架之外工作,您首先必须自己将数组转换为链表,然后在调用该函数后,您需要将结果转换回数组或任何东西可打印。

所以在下面我添加了两个实用函数来做到这一点——我没有触及您提供的代码:

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;
}

// All changes are in the part below:

function arrayToList(arr) {
    return arr.reduceRight((next, val) => 
        Object.assign(new ListNode(val), { next })
    , null);
}

function listToArray(list) {
    const arr = [];
    for (let node = list; node; node = node.next) {
        arr.push(node.value);
    }
    return arr;
}

const list = arrayToList([3, 1, 2, 3, 4, 5]);
const shorter = removeKFromList(list, 3);
const result = listToArray(shorter);
console.log(result);