JavaScript中的LinkedList循环

JavaScript中的LinkedList循环,javascript,algorithm,data-structures,Javascript,Algorithm,Data Structures,我在JavaScript中遇到了以下用于检测LinkedList循环的代码,但我不清楚为什么需要“pause”变量?另外,为什么fast需要以两倍的速度增加,而不是只提前一次 var fast = linkedList; var slow = linkedList; var pause = true; while (fast = fast.next) { if (fast === slow) { return true; } if (!pause) { slow =

我在JavaScript中遇到了以下用于检测LinkedList循环的代码,但我不清楚为什么需要“pause”变量?另外,为什么
fast
需要以两倍的速度增加,而不是只提前一次

var fast = linkedList;
var slow = linkedList;
var pause = true;

while (fast = fast.next) {
  if (fast === slow) {
    return true;
  }
  if (!pause) {
    slow = slow.next;
  }
  pause = !pause
}
return false;
演练,假设while条件为真,最多迭代6次:

//first iteration ----> pause is true
    //fast = linkedList.next
    //slow = linkedList
    //pause is now false.
//second iteration ----> pause is now false!
    //fast = linkedList.next.next
    //slow = linkedList.next
    //pause is now true
//third iteration ---> pause is now true.
    //fast = linkedList.next.next.next
    //slow = linkedList.next
    //pause is now false
//fourth iteration ----> pause is now false!
    //fast = linkedList.next.next.next.next
    //slow = linkedList.next.next
    //pause is now true
//fifth iteration ---> pause is true
    //fast = linkedList.next.next.next.next.next
    //slow = linkedList.next.next
//sixth iteration ---> pause is false
    //fast = linkedList.next.next.next.next.next.next
    //slow = linkedList.next.next.next
下面是我对这个问题的最初尝试,好奇的是我最初的方法出了什么问题

var slower = linkedList.value; // this is the head value
var faster = linkedList.next; //start faster one ahead

//if there is no next value or faster itself does not have a next value
if (!faster || !faster.next || !slower.next) {
  return false;

}
//if faster ever equals slower, then there are duplicates!
if (faster === slower || faster.next === slower || faster === faster.next ||
  slower === slower.next) {
  return true;
}
// keep advancing the pointers!
else {
  faster = faster.next.next;
  slower = slower.next;
}

pause
确保
slow
在两次迭代中只前进一次。看不到您在说什么,您能再详细说明一下吗?最初
slow
fast
都将指向第一个元素。在下一次迭代中,由于
pause
true
,因此只有
fast
是高级的。因此,现在
fast
将分别指向第二个和
slow
将分别指向第一个元素。在下一次迭代中,由于
pause
false
,因此
fast
slow
都是高级的。明白了。因此,我仔细检查了算法(上面更新的代码),似乎
的移动速度是
的两倍,而在我的实现中,我认为它只需要比
快一倍。你知道为什么
fast
需要以两倍的速度移动,而不是只向前一步吗?@devdropper87,fast和slow之间的距离决定了它可以检测到的循环的最大长度。如果fast总是在前面一个,那么它将只检测长度为1的周期。