Stack vs Queue Methods in Java
Method Queue Methods Stack Methods
add(E e) / offer(E
add(E
e) e) adds element to the queueoffer(E e) adds element, returns false on failure push(E e) adds element to the stack
remove()
remove()
/ poll()removes front element (throws exception if empty)poll() removes front, returnspop()
null ifremoves
empty top element (throws exception if empt
peek() peek()
/ element()
returns front element (returns null if empty)element() returns front (throws exceptionpeek()
if empty)
returns top element (returns null if empty)
isEmpty() isEmpty() returns true if queue is empty isEmpty() returns true if stack is empty
size() size() returns number of elements in queue size() returns number of elements in stack
Queue Example:
---------------
import [Link];
import [Link];
public class QueueExample {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Queue size: " + [Link]()); // Output: 2
[Link]("Head: " + [Link]()); // Output: Apple
[Link]("Removed: " + [Link]()); // Output: Apple
[Link]("Is queue empty? " + [Link]()); // Output: false
Stack Example:
--------------
import [Link];
public class StackExample {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Stack size: " + [Link]()); // Output: 2
[Link]("Top: " + [Link]()); // Output: Banana
[Link]("Popped: " + [Link]()); // Output: Banana
[Link]("Is stack empty? " + [Link]()); // Output: false