write the cycle detection algorithm