Stack is a last-in-first-out data structure that can be easily implemented using
Array. We can simply restrict our interface that wraps an
Array to just two operations --
pop and some other useful methods to emulate stack like functionality. You can read more about stacks here.
We'll make some assumptions before we start the implementation.
array would always be the bottom of our stack.
array[n] will be the top of the stack.
size method will keep track of the size of our stack.
push should always return
pop should always return the value of the popped element.
Because arrays in Ruby are dynamic, we'll be starting off with a simple implementation of building a stack that can be grown as we add elements to it.
Stack class maintains an unbound
@store array and simply calls
push on them.
size returns the length of the array.
Modify the above example to make the
Stack class statically sized.
pop should return
nil if the stack is overflowing or underflowing respectively. Implement private predicate methods
empty? and public method
size that returns the length of the stack, and
look that returns the value on the top of the stack.