Skip to content

Instantly share code, notes, and snippets.

@matthutchinson
Last active June 22, 2017 15:40
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 matthutchinson/f3305b711f76f92d791e3d134bda986b to your computer and use it in GitHub Desktop.
Save matthutchinson/f3305b711f76f92d791e3d134bda986b to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
class LinkedListNode
attr_accessor :value, :next_node
def initialize(value, next_node = nil)
@value = value
@next_node = next_node
end
end
def print_values(list_node)
if list_node != nil
print "#{list_node.value} --> "
print_values(list_node.next_node)
else
print "nil\n"
return
end
end
class Stack
attr_reader :data
def initialize
@data = nil
end
# Push a value onto the stack
def push(value)
my_node = LinkedListNode.new(value, @data)
@data = my_node
end
# Pop an item off the stack.
# Remove the last item that was pushed onto the
# stack and return the value to the user
def pop
top_node = @data
@data = top_node.next_node
return top_node
end
end
def reverse_list(list_node)
my_stack = Stack.new
while list_node != nil
# push each value into the linked list stack
my_stack.push(list_node.value)
# move to the next value (will finish looping when next_node is nil)
list_node = list_node.next_node
end
return my_stack.pop
end
node1 = LinkedListNode.new(37, nil)
node2 = LinkedListNode.new(99, node1)
node3 = LinkedListNode.new(12, node2)
print_values(node3)
puts "-------"
reversed_list = reverse_list(node3)
print_values(reversed_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment