我正在尝试从链接列表中删除重复项,但是重复项仍然存在

我有以下类 ListNode


class ListNode {

    constructor(val) {

        this.val = val

        this.next = null

    }

}

我试图通过将值存储在哈希中来删除重复值,如果存在这些值,则不应使用这些值形成新节点;但是,我所完成的只是当前列表的副本。我不确定我在哈希中做错了什么。我的逻辑结构不正确吗?


const deleteDuplicates = (head) => {

    let newNode = new ListNode('dummy')

    let current = newNode

    let headHash = {}


    while (head) {

        if (headHash[head.val] === undefined) {

            if (newNode.next === null) newNode.next = new ListNode(head.val)

            else {

                newNode = newNode.next

                newNode.next = new ListNode(head.val)

            }

        }

        headHash = (headHash[head.val] || 0) + 1

        console.log(headHash, head.val);

        head = head.next


    }

    return current.next

}


const l = new ListNode(1)

l.next = new ListNode(1)

l.next.next = new ListNode(2)


const l2 = new ListNode(1)

l2.next = new ListNode(1)

l2.next.next = new ListNode(2)

l2.next.next.next = new ListNode(3)

l2.next.next.next.next = new ListNode(3)



console.log(deleteDuplicates(l));

console.log(deleteDuplicates(l2));


德玛西亚99
浏览 137回答 1
1回答

回首忆惘然

违规行似乎是这一行:headHash = (headHash[head.val] || 0) + 1您不必将整体分配headHash给一个值,而是必须将headHash的当前头值属性分配给一个未定义的值。请看下面的代码:class ListNode {&nbsp; constructor(val) {&nbsp; &nbsp; this.val = val;&nbsp; &nbsp; this.next = null;&nbsp; }}const deleteDuplicates = (head) => {&nbsp; let newNode = new ListNode("dummy");&nbsp; let current = newNode;&nbsp; let headHash = {};&nbsp; while (head) {&nbsp; &nbsp; if (headHash[head.val] === undefined) {&nbsp; &nbsp; &nbsp; if (newNode.next === null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newNode.next = new ListNode(head.val);&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newNode = newNode.next;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newNode.next = new ListNode(head.val);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; // headHash = (headHash[head.val] || 0) + 1 // <- offending line&nbsp; &nbsp; headHash[head.val] = (headHash[head.val] || 0) + 1; // You need to assign the value to the headHash's key, not to the headHasn itself.&nbsp; &nbsp; head = head.next;&nbsp; }&nbsp; return current.next;};const l = new ListNode(1);l.next = new ListNode(1);l.next.next = new ListNode(2);const l2 = new ListNode(1);l2.next = new ListNode(1);l2.next.next = new ListNode(2);l2.next.next.next = new ListNode(3);l2.next.next.next.next = new ListNode(3);console.log(deleteDuplicates(l));console.log(deleteDuplicates(l2));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript