Created
April 25, 2015 01:57
-
-
Save davissp14/f8eee1d04978016a2327 to your computer and use it in GitHub Desktop.
Stack using a fixed size array
This file contains hidden or 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
class Stack | |
def initialize(size=10) | |
raise "InvalidSizeInput" unless size.is_a?(Fixnum) | |
@store = Array.new(size) | |
@size = size | |
@top = 0 | |
end | |
def push(ele) | |
if full? | |
raise "overflow" | |
else | |
@store[@top] = ele | |
@top += 1 | |
end | |
end | |
def pop | |
if empty? | |
raise "underflow" | |
else | |
@top -= 1 | |
result = @store[@top] | |
@store[@top] = nil | |
result | |
end | |
end | |
private | |
def empty? | |
@top == 0 | |
end | |
def full? | |
@top == @size | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment