Javascript 编写一个函数来检测链表中的循环(Floyd&x27;s alg)。。。逻辑看起来正确,但可以';我找不到窃听器
我试图在我创建的链接列表中发现一个循环(我正在练习面试问题)。我理解弗洛伊德的乌龟兔算法所涉及的逻辑,但函数总是返回false 以下是我的链接列表:Javascript 编写一个函数来检测链表中的循环(Floyd&x27;s alg)。。。逻辑看起来正确,但可以';我找不到窃听器,javascript,linked-list,floyd-cycle-finding,cycle-detection,Javascript,Linked List,Floyd Cycle Finding,Cycle Detection,我试图在我创建的链接列表中发现一个循环(我正在练习面试问题)。我理解弗洛伊德的乌龟兔算法所涉及的逻辑,但函数总是返回false 以下是我的链接列表: class LinkedList { constructor() { this.length = 0; this.head = null; } insert(index, value) { if (index < 0 || index > this.length) { throw new
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);
我就是找不到我的函数有什么问题,我越想弄清楚它,我就变得越狭隘。。。任何指导都将不胜感激 每次插入都会创建新节点。例如,第3个和第8个节点的值均为65,但不相等(它们是不同的对象,因此
=
条件将失败)。更重要的是,它们有不同的。next
节点和slwo
和fast
迭代器在遍历第8个元素后将不会循环回第4个元素 请提供一个实际包含一个循环的图表。我刚刚阅读了一个最小的、完整的、可验证的示例的指南,我明白了为什么您要求我提供这样一个示例。然而,在我做之前先问一个问题:我的列表实际上不包含一个循环?不,你的列表不包含一个循环。它是一个链,有9个不同的节点,最后一个节点没有链接到下一个节点。@JackSurtees链表从来没有任何循环,因为链表的特点是线性且有一个端点。重复元素不会创建循环-循环会导致无限列表。您的insert
方法从未创建过这样的结构。Bergi和trincot,非常感谢。你澄清了对我来说是一个很大的理解
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);