Skip to content

Instantly share code, notes, and snippets.

@pdbradley
Created October 17, 2016 00:53
Show Gist options
  • Save pdbradley/a3d8e90bfe27c3125cbeec9de3a42779 to your computer and use it in GitHub Desktop.
Save pdbradley/a3d8e90bfe27c3125cbeec9de3a42779 to your computer and use it in GitHub Desktop.
chase stack demo
class LinkedListNode
attr_accessor :value, :next_node
def initialize(value, next_node=nil)
@value = value
@next_node = next_node
end
end
node1 = LinkedListNode.new(37)
node2 = LinkedListNode.new(99, node1)
node3 = LinkedListNode.new(12, node2)
class Stack
attr_reader :data
def initialize
@data = nil
end
def push(value)
new_top = LinkedListNode.new(value)
new_top.next_node = @data
@data = new_top
end
def pop
if @data
top_value = @data.value
@data = @data.next_node
top_value
else
nil
end
end
end
# mystack = Stack.new
# mystack.push(9)
# 9
# mystack.push(11)
# 11
# 9
# mystack.push(5)
# 5
# 11
# 9
# thing_on_top = mystack.pop
# (now thing_on_top has the value of 5)
# 11
# 9
# thing_on_top = mystack.pop
# (now thing_on_top has the value of 11)
# 9
# print_values(node3)
# at this point, list_node = node3
# print node3.value (print out 12)
# print_values(node2)
# at this point list_node = node2
# print node2.value (print out 99)
# print_values(node1)
# at this point list_node = node1
# print node2.value (print out 37)
# print_values(nil)
# at this point list_node = nil
# print nil
# return
# They want you to take a list like 1 - 3 - 5 - 9
# and give back 9 5 3 1
# 9
# 5
# 3
# 1
# pop (9)
# pop (5)
# pop (3)
# pop (1)
def print_values(list_node)
if list_node
print "#{list_node.value} --> "
print_values(list_node.next_node)
else
print "nil\n"
return
end
end
print_values(node3)
require 'pry'; binding.pry
puts 'all done'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment