Last active
August 29, 2015 14:13
-
-
Save paractmol/0b4bc01cacda582e528d to your computer and use it in GitHub Desktop.
linked_list.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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