Aside — expandCapacity
ArrayStack
An example ArrayStack containing four elements. The elements are always stored contiguously as the bottom is
always index 0 and there was no way to introduce “holes” between index 0 and top.
With the
ArrayStack, the adding and removing only happened from one end of the arrayThe array will always be contiguous from the bottom of the stack (index
0) to thetop
If
expandCapacitywas ever needed, all elements would be copied to the new array such that each element would be in the same index as the old arrayThe element at index
0in the old array would be in index0of the new arrayThe element at index
1in the old array would be in index1of the new arrayThe element at index
2in the old array would be in index2of the new array…
The element at index
top - 1in the old array would be in indextop - 1of the new array
ArrayQueue
For ideas #1 and #2 of the
ArrayQueue, anexpandCapacitylike the one used for theArrayStackwould work just fineThe added complexity of
expandCapacityfor idea #3 of theArrayQueueis caused by the “circle” array ideaThe “circular” array idea allows for the elements to not be contiguous in the underlying linear array
Consider using the
ArrayStackimplementation’sexpandCapacityfor idea #3 of theArrayQueueDouble the size of the array and copy the elements over
Example of idea #3 for the ArrayQueue that had wrapping elements after performing the expandCapacity used in
the ArrayStack. Notice that the third element, which is at index 0, should be immediately following the
second element, which is at index 3. Instead, index 4 contains no element, meaning there is a “hole”.
Note that
frontis2andrearis2The order of the elements’ indices in the queue from first to last is
2,3,0,1Idea #3’s
ArrayQueuemanages this ordering with the index update rule ofrear = (rear + 1) % queue.length
Even after the
expandCapacitythere is no room for any new element in index2