Last active
February 11, 2016 06:39
-
-
Save astronomy88/7084e477aa03ce7ddbfe to your computer and use it in GitHub Desktop.
Implementing a Stack class using an Array
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
class Stack | |
attr_reader :length, :stack | |
def initialize(size=1) | |
@stack = Array.new(size) | |
@length = 0 | |
end | |
def is_empty? | |
return @length == 0 | |
end | |
def resize(max) | |
temp = Array.new(max) | |
for i in 0..@length-1 | |
temp[i] = @stack[i] | |
end | |
@stack = temp | |
end | |
def push item | |
resize(@length * 2) if @length == @stack.length | |
@stack[@length] = item | |
@length += 1 | |
@stack | |
end | |
def pop | |
#-- Don't pop if stack is empty | |
return nil if self.is_empty? | |
temp = @stack[@length - 1] | |
@stack[@length - 1] = nil | |
@length -= 1 | |
if (@length > 0 && @length == (@stack.length / 4)) | |
resize(@stack.length / 2) | |
end | |
temp | |
end | |
def each | |
@length.downto(0) do |i| | |
yield @stack[i] if block_given? | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment