我遇到了以下用于检测JavaScript中LinkedList Cycles的代码,但我不清楚为什么需要“暂停”变量?另外,为什么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;
演练,假设条件为真,最多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;
}