The ArrayQueue from the previous section is a data structure for representing a sequence that allows us to efficiently add to one end of the sequence and remove from the other end. The ArrayDeque data structure allows for efficient addition and removal at both ends. This structure implements the List interface by using the same circular array technique used to represent an ArrayQueue.
The
and
operations on an ArrayDeque are
straightforward. They get or set the array element
.
The implementation of
is a little more interesting. As
usual, we first check if
is full and, if necessary, call
to resize
. Remember that we want this operation to be
fast when
is small (close to 0) or when
is large (close to
). Therefore, we check if
. If so, we shift the
elements
left by one position. Otherwise
(
), we shift the elements
right
by one position. See Figure 2.3 for an illustration of
and
operations on an ArrayDeque.
By doing the shifting in this way, we guarantee that
never
has to shift more than
elements. Thus, the running
time of the
operation (ignoring the cost of a
operation) is
.
The implementation of the
operation is similar. It either
shifts elements
right by one position or shifts
the elements
left by one position depending
on whether
. Again, this means that
never spends
more than
time to shift elements.
The following theorem summarizes the performance of the ArrayDeque data structure:
opendatastructures.org