Stack implementation in Ruby
Below is a stack implemented with a linked list.
class Stack
private class Node
attr_accessor :data, :next
def initialize(data)
@data = data
@next = nil
end
end
def initialize
@top = nil
@size = 0
end
def push(data)
node = Node.new(data)
if @top == nil
@top = node
else
node.next = @top
@top = node
end
@size += 1
end
def pop
if @top != nil
ret = @top.data
@top = @top.next
@size -= 1
end
ret
end
def size
@size
end
def peek
return @top.data if @top != nil
end
def empty?
return @size == 0
end
def each
curr = @top
while curr
yield curr
curr = curr.next
end
end
def to_s
if @size != 0
each { |node| print "#{node.data} "}
puts
end
end
alias_method :length, :size
end
And the following is implemented with an array.
class StackArray
def initialize
@top = []
end
def push(data)
@top.unshift(data)
end
def pop
@top.shift
end
def size
@top.size
end
def peek
@top.first
end
def empty?
return @top.size == 0
end
def each
idx = 0
while idx < @top.size
yield @top[idx]
idx += 1
end
end
def to_s
if @top.size != 0
each { |x| print "#{x} "}
puts
end
end
alias_method :length, :size
end