gpt4 book ai didi

javascript - 编写一个函数来检测链表中的循环(Floyd's alg)...逻辑看起来正确,但找不到错误

转载 作者:行者123 更新时间:2023-12-02 23:46:57 26 4
gpt4 key购买 nike

我正在尝试检测我创建的链接列表中的循环(我正在练习面试问题)。我理解弗洛伊德龟兔赛跑算法中涉及的逻辑,但该函数总是返回 false...

这是我的链接列表:

class LinkedList {
constructor() {
this.length = 0;
this.head = null;
}
insert(index, value) {
if (index < 0 || index > this.length) {
throw new Error("Index error");
}
const newNode = {
value
};
if (index == 0) {
newNode.next = this.head;
this.head = newNode;
} else {
const node = this._find(index - 1);
newNode.next = node.next;
node.next = newNode;
}
this.length++;
}
...
}

//Inserting values
const linkedList = new LinkedList();
linkedList.insert(0, 12);
linkedList.insert(1, 24);
linkedList.insert(2, 65);
linkedList.insert(3, 23);
linkedList.insert(4, 9);
linkedList.insert(5, 7);
linkedList.insert(6, 13);
linkedList.insert(7, 65);
linkedList.insert(8, 20);

这是我的循环检测函数,即使存在循环它也会返回 false:

 function containsCycle(firstNode) {
// Start both at beginning
let slow = firstNode;
let fast = firstNode;
// Until end of the list
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
// fast is about to "lap" slow
if (fast === slow) {
return true;
}
}
// fast hit the end of the list
return false;
}

//Calling function
containsCycle(linkedList.head);

我只是找不到我的功能出了什么问题,而且我越想弄清楚,我的思想就越狭隘......任何指导将非常感激!

最佳答案

每次插入时您都会创建新节点。例如。第三个和第八个节点的值都是 65,但不相等(它们是不同的对象,因此 === 条件将失败)。更重要的是,它们具有不同的 .next 节点,并且您的 slwofast 迭代器在遍历第 8 个元素后不会循环回第 4 个元素。

关于javascript - 编写一个函数来检测链表中的循环(Floyd's alg)...逻辑看起来正确,但找不到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55817200/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com