Stacks and Queues – In-Depth Summary
Stacks and Queues are fundamental linear data structures that store and organize data in
specific orders. They are used heavily in algorithms, memory management, and real-world
systems like job scheduling and browser history tracking.
📚 Stack – LIFO (Last In, First Out)
A Stack allows access only to the last inserted element. The most recently added item is the
first to be removed—like a stack of plates.
🧠 Operations:
● push(item) → Add item to the top
● pop() → Remove and return top item
● peek() or top() → View the top item without removing it
● isEmpty() → Check if the stack is empty
🛠 Java Example:
java
CopyEdit
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.pop();
🔍 Use Cases:
● Function call stack
● Undo/Redo systems
● Parsing expressions (e.g., balanced parentheses)
● Depth-First Search (DFS)
🚶 Queue – FIFO (First In, First Out)
A Queue processes items in the order they were added. The first element added is the first to
be removed—like people in a line.
🧠 Operations:
● enqueue(item) → Add item at the end
● dequeue() → Remove and return item from the front
● peek() or front() → View front item
● isEmpty() → Check if the queue is empty
🛠 Java Example:
java
CopyEdit
Queue<Integer> queue = new LinkedList<>();
queue.add(10);
queue.remove();
🔍 Use Cases:
● CPU/task scheduling
● Print queues
● Breadth-First Search (BFS)
● Buffers in networking
🔄 Variations
Type Description
Deque Double-ended queue (can add/remove both
ends)
Priority Queue Elements dequeued by priority, not order
Circular Queue Wraps around when it reaches the end
⚖️ Time Complexity
Operation Stac Queu
k e
Insertion O(1) O(1)
Deletion O(1) O(1)
Access O(1) O(1)
(peek)
Note: Priority queues and deques may have different complexities depending on
implementation.
✅ Summary
● Stacks use LIFO: Last in is the first out.
● Queues use FIFO: First in is the first out.
● Used in algorithms, memory, processing flows, and system design.
● Java provides built-in support with Stack, Queue, Deque, and PriorityQueue.