Skip to content

Instantly share code, notes, and snippets.

@rudkovskyi
Last active Aug 29, 2015
Embed
What would you like to do?
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