Java Queue, Stack

FIFO: Queue  FILO: Stack


Since java 5 we can use queue by importing

import java.util.Queue;

Insert an item at the end of a queue and pop out from the head of the queue. Queue is an interface that there are several implementing classes, but the most used class is LinkedList

Queue<TreeNode> queue = new LinkedList<TreeNode>();

As a collection, it’s better to use the methods on the right side, because methods on the left side may throw Exceptions

As a linked list, queue use isEmpty method:

Insert add(e) offer(e)
Remove remove() poll()
Examine element() peek()

Poll is just a reference!


Stack extends from the vector with methods below:

boolean empty()

Tests if this stack is empty.
E peek()

Looks at the object at the top of this stack without removing it from the stack.
E pop()

Removes the object at the top of this stack and returns that object as the value of this function.
E push(E item)

Pushes an item onto the top of this stack.
int search(Object o)

Returns the 1-based position where an object is on this stack.

Deque(Double ended queue)

FIFO when inserting from the last, FILO when inserting from the head.

Insert addFirst(e) offerFirst(e) addLast(e) offerLast(e)
Remove removeFirst() pollFirst() removeLast() pollLast()
Examine getFirst() peekFirst() getLast() peekLast()

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s