Home

addFirst

addFirst is a mutator operation on double-ended queues (deques) and other structures that support insertion at the front. It inserts a new element so that it becomes the first element, preceding all existing ones. In a typical deque or linked list, adding at the front is performed in constant time.

Performance and behavior can vary by implementation. For linked-list-based deques, addFirst is usually O(1). For array-backed

Language and API differences. In Java, Deque.addFirst(e) inserts the element at the front and throws IllegalStateException

Common usage and alternatives. addFirst is often used to implement front-loaded queues, deques, or to support

deques
that
use
a
circular
buffer,
it
is
also
designed
to
be
O(1)
on
most
operations,
though
occasional
resizing
can
occur,
making
the
operation
amortized
O(1).
In
bounded
structures,
addFirst
may
fail
when
capacity
is
reached,
and
different
languages
expose
different
failure
modes.
if
the
deque
is
full;
a
related
method,
offerFirst(e),
returns
a
boolean
to
indicate
success.
In
Python,
collections.deque
uses
appendleft(x)
for
front
insertion.
In
C++,
std::deque
offers
push_front(x)
to
place
an
element
at
the
front.
Other
languages
may
use
different
names
but
generally
provide
a
front-insert
capability
as
part
of
a
deque
or
similar
interface.
algorithms
that
require
prepending
elements.
Related
operations
include
addLast
(or
push_back),
removeFirst,
removeLast,
and
peekFirst.
Understanding
the
specific
semantics
and
capacity
behavior
of
the
target
language
or
library
is
important
for
correct
usage.