Skip to content

Instantly share code, notes, and snippets.

@aespaldi
Last active December 11, 2015 19:48
Show Gist options
  • Save aespaldi/4650906 to your computer and use it in GitHub Desktop.
Save aespaldi/4650906 to your computer and use it in GitHub Desktop.
# A very basic Stack implemented with an array
class Stack
attr_reader :length, :top
def initialize(size = 1)
@length = size
self.reset
end
def empty?
@top.nil?
end
def full?
@top == @length - 1
end
def singleton?
@top == 0
end
def push(element)
raise "Stack Overflow - The stack is full" if self.full?
if self.empty?
@top = 0
else
@top = @top + 1
end
@array[@top] = element
end
def pop
raise "Stack Underflow - The stack is empty" if self.empty?
x = @array[@top]
if self.singleton?
@top = nil
else
@top = @top - 1
end
return x
end
def reset
@array = Array.new(@length)
@top = nil
end
alias_method :reset!, :reset
def size
@array.size
end
def first
@array.first
end
def last
@array[@top]
end
def each
@array.each do
yield
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment