Commit 50efcb1
Changed files (1)
lib/detect_circles.rb
@@ -1,22 +1,35 @@
<<-DOC
-[2:10 PM] Marvin Liu: You are given a single linked list, and you are asked to determine if there is a circle inside it
-[2:11 PM] Marvin Liu: A circle means, a -> b -> c -> b, then it is a circle
+You are given a single linked list, and you are asked to determine if there is a circle inside it
+A circle means, a -> b -> c -> b, then it is a circle
DOC
+require 'byebug'
-def circle?(head)
- true
+def circle?(list)
+ tortoise, hare = list, list.next_item
+
+ until hare.nil?
+ return true if tortoise == hare
+ tortoise = tortoise.next_item
+ hare = hare.next_item.next_item
+ end
+
+ return false
end
class Node
attr_reader :next_item, :value
def initialize(value)
- @value
+ @value = value
end
def add(value)
@next_item = value.is_a?(Node) ? value : Node.new(value)
end
+
+ def inspect
+ "#{object_id} #{value}"
+ end
end
a = Node.new("A")