Skip to content

Instantly share code, notes, and snippets.

@astronomy88
Last active February 11, 2016 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astronomy88/7084e477aa03ce7ddbfe to your computer and use it in GitHub Desktop.
Save astronomy88/7084e477aa03ce7ddbfe to your computer and use it in GitHub Desktop.
Implementing a Stack class using an Array
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