Created
November 6, 2015 19:28
-
-
Save prehnRA/29d261fb50402aac1b1f to your computer and use it in GitHub Desktop.
Cycle detector
This file contains hidden or 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 Node | |
attr_accessor :next | |
def initialize(nxt) | |
@next = nxt | |
end | |
def self.linked_list_with_cycle | |
node = linked_list_without_cycle | |
node.next.next.next = node | |
end | |
def self.linked_list_without_cycle | |
node3 = new(nil) | |
node2 = new(node3) | |
new(node2) | |
end | |
end | |
# Using https://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare | |
def cycle?(node) | |
slow = node | |
fast = node | |
loop do | |
slow = slow.next | |
fast = fast.try(:next).try(:next) | |
return false if slow.nil? || fast.nil? | |
return true if slow == fast | |
end | |
end | |
# "Tests" | |
if cycle?(Node.linked_list_with_cycle) == true | |
puts "Hurray!" | |
else | |
puts "Booo" | |
end | |
if cycle?(Node.linked_list_without_cycle) == false | |
puts "Hurray!" | |
else | |
puts "Booo" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment