Difference between Queue and Stack
Queue
- Purpose: A Queue is a linear data structure that follows the FIFO (First In, First Out) principle, where elements are inserted at the rear and removed from the front.
- Operations: Queues typically support operations like enqueue (add an element to the rear), dequeue (remove an element from the front), peek (retrieve the element at the front without removing it), and isEmpty (check if the queue is empty).
- Usage: Queues are commonly Queue and Stack used in scenarios where elements need to be processed in the order they were added, such as task scheduling, breadth-first search algorithms, and message queues.
Stack
- Purpose: A Stack is a linear data structure that follows the LIFO (Last In, First Out) principle, where elements are inserted and removed from the same end, known as the top of the stack.
- Operations: Stacks typically support operations Queue and Stack like push (add an element to the top), pop (remove the element from the top), peek (retrieve the element at the top without removing it), and isEmpty (check if the stack is empty).
- Usage: Stacks are commonly used in scenarios where elements need to be processed in reverse order of their insertion, such as function call stack in programming, expression evaluation, and undo mechanisms.
Table of Contents
Example - Queue (using LinkedList):
java
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
// Create a Queue using LinkedList
Queue<Integer> queue = new LinkedList<>();
// Enqueue elements to the queue
queue.offer(1);
queue.offer(2);
queue.offer(3);
// Dequeue and print elements
while (!queue.isEmpty()) {
System.out.println("Dequeued: " + queue.poll());
}
}
}
Example
Example - Stack (using ArrayDeque):
java
import java.util.ArrayDeque;
import java.util.Deque;
public class StackExample {
public static void main(String[] args) {
// Create a Stack using ArrayDeque
Deque<Integer> stack = new ArrayDeque<>();
// Push elements to the stack
stack.push(1);
stack.push(2);
stack.push(3);
// Pop and print elements
while (!stack.isEmpty()) {
System.out.println("Popped: " + stack.pop());
}
}
}
Queue example
In the Queue example, we use a LinkedList to implement a Queue. We enqueue elements using the offer() method and dequeue elements using the poll() method until the queue becomes empty. In the Stack example, we use an ArrayDeque to implement a Stack. We push elements onto the stack using the push() method and pop elements from the stack using the pop() method until the stack becomes empty.
These examples demonstrate the fundamental differences between Queue and Stack data structures based on their respective principles of FIFO and LIFO.