Solution to Exercise 3.19
clean99 opened this issue · comments
Define a fast pointer and a slow pointer. The fast pointer goes forward 2 steps every time, while the slow pointer goes forward 1 step every time. If there is a cycle in the list, the fast pointer will eventually catch up with the slow pointer.
function contains_cycle(x) {
if(is_null(x)) {
return false;
}
function detect_cycle(fast, slow) {
if(is_null(fast) || is_null(tail(fast))) {
return false;
}
if(fast === slow) {
return true;
}
return detect_cycle(tail(tail(fast)), tail(slow));
}
return detect_cycle(tail(x), x);
}