Stack, Queue, and Deque Methods in Java
Method Queue Methods Stack Methods Deque Methods
add(E e) / offer(E e) add(E e) / offer(E e) push(E e) addFirst(E e) / addLast(E e)
remove() / poll() remove() / poll() pop() removeFirst() / removeLast()
peek() / element() peek() / element() peek() peekFirst() / peekLast()
isEmpty() isEmpty() isEmpty() isEmpty()
size() size() size() size()
Method Summaries and Examples:
-------------------------------
1. add(E e) / offer(E e) (Queue & Deque):
- Queue: add(E e) adds the element to the rear of the queue. offer(E e) does the same but returns false on failure.
- Deque: addFirst(E e) adds the element to the front. addLast(E e) adds the element to the rear.
Example for Queue:
Queue<String> queue = new LinkedList<>();
[Link]("Apple");
[Link]("Banana");
Example for Deque:
Deque<String> deque = new LinkedList<>();
[Link]("Apple");
[Link]("Banana");
2. remove() / poll() (Queue & Deque):
- Queue: remove() removes and returns the element at the front, throws an exception if empty. poll() returns null if empty.
- Deque: removeFirst() removes and returns the front element. removeLast() removes and returns the rear element.
Example for Queue:
[Link]([Link]()); // Output: Apple
[Link]([Link]()); // Output: Banana
Example for Deque:
[Link]([Link]()); // Output: Apple
[Link]([Link]()); // Output: Banana
3. peek() / element() (Queue & Deque):
- Queue: peek() returns the front element without removing it (null if empty). element() is similar but throws an exception if empty.
- Deque: peekFirst() returns the front element without removing it. peekLast() returns the rear element.
Example for Queue:
[Link]([Link]()); // Output: Banana
[Link]([Link]()); // Output: Banana
Example for Deque:
[Link]([Link]()); // Output: Apple
[Link]([Link]()); // Output: Banana
4. isEmpty() (Queue, Stack & Deque):
- Returns true if the queue, stack, or deque is empty.
Example:
[Link]([Link]()); // Output: false
5. size() (Queue, Stack & Deque):
- Returns the number of elements in the queue, stack, or deque.
Example:
[Link]([Link]()); // Output: 1