3.19 Exercise 3.19
We can detect cycles in constant space by using two pointers into the list.
The basic idea is that we have the two pointers traverse the list at
different speeds – one moving forward one entry at a time, and the other
by two. At some point, if the list contains a cycle, these two pointers
will point to the same thing. Alternatively, if a pointer reaches the end
of the list before this happens, we know we don’t have a cycle.
(define (tortoise-hare l) | (define (loop tortoise hare) | (cond ((or (null? tortoise) | (null? hare)) | #f) | ((eq? tortoise hare) #t) | (else | (let ((t2 (cdr tortoise)) | (h2 (cdr hare))) | (if (null? h2) | (loop t2 h2) | (loop t2 (cdr h2))))))) | (loop l (cdr l))) |
|