class Node
attr_reader :data
attr_accessor :next
def initialize(data)
@data = data
end
def to_s
output = (@next != nil) ? "#{@next}, " : ""
output += "#{@data}"
output
end
end
class Stack
attr_reader :top
def initialize
puts self.to_s
end
def push(data)
node = Node.new(data)
node.next = @top
@top = node
puts "push #{data}"
puts self.to_s
return data
end
def pop
if @top == nil
return nil
end
data = @top.data
@top = @top.next
puts "pop #{data}"
puts self.to_s
return data
end
def to_s
"Stack: [#{@top}]"
end
end
stack = Stack.new
stack.pop
(1..3).each { |i| stack.push(i) }
5.times { stack.pop }
To embed this project on your website, copy the following code and paste it into your website's HTML: