Skip to content

Instantly share code, notes, and snippets.

@arjans
Created November 18, 2016 19:59
Show Gist options
  • Save arjans/d95a490aeba73c4d0e03a51dfc8fe4ab to your computer and use it in GitHub Desktop.
Save arjans/d95a490aeba73c4d0e03a51dfc8fe4ab to your computer and use it in GitHub Desktop.
Stack in Ruby
# 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