The idea is to have two iterators; the hare and the tortoise. The hare runs along the list faster than the tortoise and if the list has a cycle, the hare will eventually overtake the tortoise. The following code illustrates the algorithm:
public boolean hasCycle(Node root){ Node tortoise = root; Node hare = tortoise.next; while (hare != tortoise) { // tortoise moves one place tortoise = tortoise.next; // hare moves two places hare = hare.next; if (hare != null) { hare = hare.next; } if (tortoise == null || hare == null) { // end of list, no cycles return false; } } return true; }(This is an interview question.)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.