Last active
December 11, 2015 19:48
-
-
Save aespaldi/4650906 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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