mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
28 lines
516 B
Ruby
28 lines
516 B
Ruby
|
# Definition for singly-linked list.
|
||
|
# class ListNode
|
||
|
# attr_accessor :val, :next
|
||
|
# def initialize(val)
|
||
|
# @val = val
|
||
|
# @next = nil
|
||
|
# end
|
||
|
# end
|
||
|
|
||
|
# @param {ListNode} head
|
||
|
# @return {ListNode}
|
||
|
|
||
|
require 'set'
|
||
|
|
||
|
def detectCycle(head)
|
||
|
def detectCycleRec(node, seen)
|
||
|
if node == nil then
|
||
|
return node
|
||
|
elsif seen.add?(node) == nil then
|
||
|
return node
|
||
|
end
|
||
|
|
||
|
return detectCycleRec(node.next, seen)
|
||
|
end
|
||
|
|
||
|
detectCycleRec(head, Set.new)
|
||
|
end
|