Created
June 22, 2017 16:06
-
-
Save pdbradley/936635a9ff6997b895ca956d13dae360 to your computer and use it in GitHub Desktop.
cycle_detector.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CycleDetector | |
def initialize(list) | |
@tortoise = list | |
@hare = list.next_node if list | |
end | |
def self.detect(list) | |
self.new(list).detect | |
end | |
def detect | |
while list_continues? | |
move_tortoise | |
move_hare | |
return true if @tortoise == @hare | |
end | |
return false | |
end | |
private | |
def move_hare | |
if @hare.next_node | |
@hare = @hare.next_node.next_node | |
else | |
@hare = nil | |
end | |
end | |
def move_tortoise | |
@tortoise = @tortoise.next_node | |
end | |
def list_continues? | |
@tortoise && @hare | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment