Floyd’s cycle-finding algorithm using PHP

Some days ago I was in an interview for a position at a company when they asked me to do a function which detects if a list is either cyclic or acyclic. I need to be honest, I didn’t know how to solve the problem and I had a limited time to solve the question then I couldn’t wonder on how to solve that for ages then I googled it. I found the Floyd’s cycle-finding algorithm, also known as “the tortoise and the hare algorithm” or “the turtle and the rabbit algorithm”. I found some examples in languages such as Java and Python but nothing using PHP, then I did it by my own based on what I saw. The result code is below:

I hope this snippet can help anybody out there.

Facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

2 thoughts on “Floyd’s cycle-finding algorithm using PHP”

    1. Hi Juan,

      Yes Node is a class, very simple but it’s a class.


      class Node{
      public $next;
      }

      This would do the trick.

Leave a Reply

Your email address will not be published. Required fields are marked *