Created
November 18, 2016 19:59
-
-
Save arjans/d95a490aeba73c4d0e03a51dfc8fe4ab to your computer and use it in GitHub Desktop.
Stack in Ruby
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
# Implementing a stack for algorithm study group. | |
# Can't use pop, <<, +, or any Ruby methods that would defeat the purpose of this exercise. | |
class Stack | |
def initialize | |
@bottom = 3 # zero-indexed | |
@top = 3 # zero-indexed | |
@items = [nil,nil,nil,nil] | |
end | |
def empty? | |
@top == @bottom | |
end | |
def pop | |
if empty? | |
"Underflow" | |
else | |
@top += 1 | |
item = @items[@top] | |
@items[@top] = nil | |
puts @items.inspect | |
item | |
end | |
end | |
def push(x) | |
if @top == -1 | |
"Overflow" | |
else | |
@items[@top] = x | |
@top -= 1 | |
@items | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment