source-academy / sicp

XML sources of SICP and SICP JS, and support for generating Interactive SICP JS, PDF, e-book and comparison editions

Home Page:https://sourceacademy.org/sicpjs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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);
}