Skip to content

Instantly share code, notes, and snippets.

@paractmol
Last active August 29, 2015 14:13
Show Gist options
  • Save paractmol/0b4bc01cacda582e528d to your computer and use it in GitHub Desktop.
Save paractmol/0b4bc01cacda582e528d to your computer and use it in GitHub Desktop.
linked_list.rb
class Node
attr_accessor :next_item, :value
def initialize(next_item, value)
@next_item = next_item
@value = value
end
def reversed
@a = []
@n = @value
iterate_items { @a.unshift(@n) }
@a
end
private
def iterate_items
yield if block_given?
if @next_item.respond_to?(:value)
@n = @next_item.value
@next_item = @next_item.next_item
iterate_items {
yield if block_given?
}
end
end
end
x = Node.new(Node.new(Node.new(Node.new(Node.new(Node.new(nil, 8),1), 0), 2), 3), 4)
puts x.reversed.inspect
# => [8, 1, 0, 2, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment