18: Shrinkable Stack
Submit this homework using Gradescope. You can type up your answers, or write legibly and scan them. Do not attempt to submit a paper copy in class, as it will not be accepted.
In lecture we built a bounded array-based stack that threw an Exception whenever too many elements were pushed to the stack. But you can imagine a stack whose backing array
grows as needed; we saw this much earlier in the semester. Suppose your colleague created UnboundedArrayStack
which modifies BoundedArrayStack
by doubling the size of the backing array whenever an element is pushed and the array has run out of room to store new elements.
Unfortunately, if we push()
to our stack a large number of times (think millions of times) and then call pop()
a large number of times (think millions of times), we will have a huge array that we are no longer using. To fix this we want to write a new version of pop()
that halves the size of the backing array whenever the number of elements on the stack is less than one fourth the length of the array. Checking the size of the stack, and the subsequent shrinking, should be done before removing the element.
There is one last subtlety! We don’t want our array to get too small, so we should ensure that our array never gets smaller than 8 elements.
(3 points) Update the pop()
method of BoundedArrayStack
required to make it into an UnboundedArrayStack
(assume that the new push()
method making the stack unbounded has already been implemented); show the full signature and body of any method(s) you modify or add. Be sure your new method(s) still implement the interface!