Aside — expandCapacity
ArrayStack
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
expandCapacity
was 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
0
in the old array would be in index0
of the new arrayThe element at index
1
in the old array would be in index1
of the new arrayThe element at index
2
in the old array would be in index2
of the new array…
The element at index
top - 1
in the old array would be in indextop - 1
of the new array
ArrayQueue
For ideas #1 and #2 of the
ArrayQueue
, anexpandCapacity
like the one used for theArrayStack
would work just fineThe added complexity of
expandCapacity
for idea #3 of theArrayQueue
is 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
ArrayStack
implementation’sexpandCapacity
for idea #3 of theArrayQueue
Double the size of the array and copy the elements over
Note that
front
is2
andrear
is2
The order of the elements’ indices in the queue from first to last is
2
,3
,0
,1
Idea #3’s
ArrayQueue
manages this ordering with the index update rule ofrear = (rear + 1) % queue.length
Even after the
expandCapacity
there is no room for any new element in index2