Hatefiend Hatefiend - 2 months ago 6
Java Question

Java - LinkedList push() pop() implies it is a stack, not a queue?

In my data structures class, I learned that a

LinkedList
is a queue. Like a line in real life, the first person who gets into the line will be the first person who leaves. Makes sense. As seen below, a
ListedList
implements a
Queue
which has a FIFO (first in first out) procedure.

But if you look at the descriptions for the methods
push(E)
and
pop()
, they read as follows:

push(E)


Pushes an element onto the stack represented by this list. In other words, inserts the element at the front of this list.


pop()


Pops an element from the stack represented by this list. In other words, removes and returns the first element of this list.


That's.... not a queue. That's a stack. The first element that goes into the LinkedList via
push
cannot be accessed by
pop
until every element added after it has been
pop()
'ed.

Why is this? I get that LinkedLists can be both used as a stack (if you only use
addFirst(E)
and
removeFirst()
) and can be used as a queue (if you only use
addFirst(E)
and
removeLast()
or vice versa) so why is it like this? I feel like
pop()
should remove and return the last element, OR
push(E)
should add the element at the end of the
LinkedList
. Then it would make more sense.

TLDR: Why does
LinkedList
's
push
and
pop
imply it works as a stack when
LinkedList
actually implements
Queue
instead.

enter image description here

Answer

Push() and pop() are by convention operations related to Stacks (Deque, more specifically in this context) and that's why you should expect your LinkedList to work that way when you use those method. If you want your LinkedList to work as a Queue instead (it implements the Queue interface) the methods you want to use (as stated in the Documentation) are add() and remove().

See LinkedList Documentation