Skip to content

Instantly share code, notes, and snippets.

@DiegoSalazar
Created December 29, 2015 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DiegoSalazar/0032480c70e4ed6abf44 to your computer and use it in GitHub Desktop.
Save DiegoSalazar/0032480c70e4ed6abf44 to your computer and use it in GitHub Desktop.
detects and counts loop size in a singly linked list
def loop_size(node)
0.tap do |idx|
begin
if node.instance_variable_get :@idx
return idx - node.instance_variable_get(:@idx)
else
node.instance_variable_set :@idx, idx
idx += 1
end
end while node = node.next
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment