Skip to content

Instantly share code, notes, and snippets.

@DiegoSalazar DiegoSalazar/scratch.rb

Last active May 4, 2017
Embed
What would you like to do?
Linked list reversal solutions
# A node of a linked list
class Node
attr_reader :value, :next_node
def initialize(value, next_node = nil)
@value = value
@next_node = next_node
end
def reverse(reversed = nil)
node = Node.new value, reversed
next_node ? next_node.reverse(node) : node
end
def reverse!(node = self, reversed = reverse)
@value = reversed.value
next_node ? next_node.reverse!(node, reversed.next_node) : node
end
def to_s
"<#{object_id} #{@value}> -> #{next_node.nil? ? "nil\n" : next_node.to_s}"
end
end
linked_list = Node.new(1, Node.new(2, Node.new(3, Node.new(4))))
puts "LinkedList: #{linked_list}"
puts "Non-mutate Reverse: #{linked_list.reverse}"
puts "Mutate Reverse: #{linked_list.reverse!}"
@DiegoSalazar

This comment has been minimized.

Copy link
Owner Author

DiegoSalazar commented Feb 2, 2017

Output:

[Running] ruby "/Users/diego/Desktop/scratch.rb"
LinkedList:           <70356388315820 1> -> <70356388315840 2> -> <70356388315880 3> -> <70356388315900 4> -> nil
Non-mutate Reverse:   <70356388315280 4> -> <70356388315320 3> -> <70356388315340 2> -> <70356388315360 1> -> nil
Mutate Reverse:       <70356388315820 4> -> <70356388315840 3> -> <70356388315880 2> -> <70356388315900 1> -> nil

[Done] exited with code=0 in 0.038 seconds

Note: digits in between <> represent the object_id and value i.e. proving that the object is the same or different object in memory .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.