SICP Exercise 3.18 detect cycle

Exercise 3.18.  Write a procedure that examines a list and determines whether it contains a cycle, that is, whether a program that tried to find the end of the list by taking successive cdrs would go into an infinite loop. Exercise 3.13 constructed such lists.

SOLUTION

This program expects an ordinary linked list as in exercise 3.13. If given a more complex structure with multiple cycles, it will miss detecting cycles that don't lie on the 'main' path. The 'main' path is the path traversed by successive cdrs from the root pair. I deliberately kept it simple. I reasoned that if we want to write a more generic cycle detector that can find all cycles in a complex structure, then this program can be used as a component there. This will allow us to keep modularity in our design.

The code is here:

Exercise 3.18 detect cycle

Comments

Popular posts from this blog

SICP Exercise 2.56 differentiation rule

SICP Exercise 1.28 (Miller-Rabin Test)

SICP Exercise 4.18 a alternative strategy for interpreting internal definitions