đĨ Stacks - LIFO (Last In, First Out)
What is a Stack?
A Stack is an Abstract Data Type (ADT) that stores arbitrary objects following the Last-In First-Out (LIFO) principle. Think of it like a spring-loaded plate dispenser - the last plate you put on top is the first one you take off!
Stack Visualization
LIFO: Element 'd' was inserted last, so it will be removed first
đ Key Characteristics:
- LIFO Ordering: Last element inserted is the first to be removed
- Restricted Access: Can only access the top element
- Dynamic Size: Grows and shrinks with push/pop operations
âī¸ Stack Operations
Main Operations
1. push(object) - Insert Element
Adds an element to the top of the stack
2. pop() - Remove and Return Element
Removes and returns the element at the top of the stack
Auxiliary Operations
3. top() - Peek at Top Element
Returns the top element without removing it
4. size() - Get Stack Size
Returns the number of elements in the stack
5. isEmpty() - Check if Empty
Checks whether the stack contains any elements
Stack Interface in Java
đ Operation Example Walkthrough
| Operation | Return Value | Stack Contents | Size |
|---|---|---|---|
| push(5) | â | (5) | 1 |
| push(3) | â | (5, 3) | 2 |
| size() | 2 | (5, 3) | 2 |
| pop() | 3 | (5) | 1 |
| isEmpty() | false | (5) | 1 |
| pop() | 5 | () | 0 |
| isEmpty() | true | () | 0 |
| pop() | null | () | 0 |
| push(7) | â | (7) | 1 |
| push(9) | â | (7, 9) | 2 |
| top() | 9 | (7, 9) | 2 |
| push(4) | â | (7, 9, 4) | 3 |
| pop() | 4 | (7, 9) | 2 |
đģ Stack Implementation
Array-Based Stack Implementation
Concept
A simple implementation using an array where:
- Elements are added from left to right
- Variable
ttracks the index of the top element - Initially,
t = -1(no elements yet)
Array Stack Structure
t = 2 (pointing to 'c', the top element)
Key Algorithms
size() Algorithm
pop() Algorithm
push(o) Algorithm
Java Implementation
â ī¸ Limitations of Array-Based Stack
- Fixed Size: Maximum size must be defined in advance
- Space Waste: May allocate more space than needed
- FullStackException: Throws exception when trying to push to full stack
đ¯ Applications of Stacks
Direct Applications
đ Web Browser History
Browser's back button uses a stack to track visited pages. Most recent page is on top!
âŠī¸ Undo Operations
Text editors use stacks to implement undo. Each action is pushed; undo pops the last action.
â JVM Method Calls
Java Virtual Machine uses a call stack to manage method invocations and returns.
đ Expression Evaluation
Evaluating arithmetic expressions and handling operator precedence.
Parentheses Matching Example
Problem: Check if parentheses are balanced
Each opening bracket "(", "{", "[" must pair with matching closing bracket ")", "}", "]"
| Expression | Valid? |
|---|---|
| ( )(( )){([( )])} | â Correct |
| ((( )(( )){([( )])}) | â Correct |
| )(( )){([( )])} | â Incorrect (starts with closing) |
| ({[ ])} | â Incorrect (mismatched) |
| ( | â Incorrect (unclosed) |
Arithmetic Expression Evaluation
Example: 14 - 3 * 2 + 7
Using operator precedence (* before +/-) and left-to-right evaluation:
- Evaluate: 3 * 2 = 6
- Evaluate: 14 - 6 = 8
- Evaluate: 8 + 7 = 15
Result: 15
Using Two Stacks:
- opStk: Holds operators (+, -, *, /)
- valStk: Holds operand values
Strategy: Push operators, but first pop and perform higher/equal precedence operations
đļ Queues - FIFO (First In, First Out)
What is a Queue?
A Queue is an Abstract Data Type (ADT) that stores arbitrary objects following the First-In First-Out (FIFO) principle. Think of it like a waiting line - the first person to arrive is the first to be served!
Queue Visualization
Front (a) â â Rear (d)
Element 'a' was inserted first, so it will be removed first
đ Key Characteristics:
- FIFO Ordering: First element inserted is the first to be removed
- Two-Ended Access: Insert at rear, remove from front
- Fair Processing: Elements processed in order of arrival
âī¸ Queue Operations
Main Operations
1. enqueue(object) - Insert at Rear
Adds an element to the rear (end) of the queue
2. dequeue() - Remove from Front
Removes and returns the element at the front of the queue
Auxiliary Operations
3. first() - Peek at Front
Returns the front element without removing it
4. size() - Get Queue Size
5. isEmpty() - Check if Empty
Queue Interface in Java
đ Operation Example Walkthrough
| Operation | Return Value | Queue Contents | Size |
|---|---|---|---|
| enqueue(5) | â | (5) | 1 |
| enqueue(3) | â | (5, 3) | 2 |
| dequeue() | 5 | (3) | 1 |
| enqueue(7) | â | (3, 7) | 2 |
| dequeue() | 3 | (7) | 1 |
| first() | 7 | (7) | 1 |
| dequeue() | 7 | () | 0 |
| dequeue() | null | () | 0 |
| isEmpty() | true | () | 0 |
| enqueue(9) | â | (9) | 1 |
| enqueue(7) | â | (9, 7) | 2 |
| size() | 2 | (9, 7) | 2 |
| enqueue(3) | â | (9, 7, 3) | 3 |
| enqueue(5) | â | (9, 7, 3, 5) | 4 |
| dequeue() | 9 | (7, 3, 5) | 3 |
đģ Queue Implementation
Array-Based Circular Queue
Concept
Uses an array of size N in a circular fashion:
f= index of the front elementsz= number of stored elementsr = (f + sz) mod N= first empty slot past rear
Normal Configuration
Wrapped-Around Configuration
Queue wraps around using modulo arithmetic
Key Algorithms
enqueue(o) Algorithm
dequeue() Algorithm
Java Implementation
Queue Applications
đ Waiting Lists
Customer service queues, print job queues, task scheduling
đ¨ī¸ Resource Sharing
Printer queues, CPU scheduling, shared resource access
đ Round Robin Scheduling
Fair time-sharing systems, process scheduling
đ BFS Algorithm
Breadth-First Search in graphs and trees
Round Robin Scheduler
Implement fair resource sharing by repeatedly:
e = Q.dequeue()- Get next task- Service element e - Process the task
Q.enqueue(e)- Return to back of queue
⥠Performance & Complexity Analysis
Stack Performance
| Operation | Array Implementation | Linked List Implementation |
|---|---|---|
| push() | O(1) | O(1) |
| pop() | O(1) | O(1) |
| top() | O(1) | O(1) |
| size() | O(1) | O(1) |
| isEmpty() | O(1) | O(1) |
| Space | O(N) - fixed size | O(n) - dynamic |
Queue Performance
| Operation | Array Implementation | Linked List Implementation |
|---|---|---|
| enqueue() | O(1) | O(1) |
| dequeue() | O(1) | O(1) |
| first() | O(1) | O(1) |
| size() | O(1) | O(1) |
| isEmpty() | O(1) | O(1) |
| Space | O(N) - fixed size | O(n) - dynamic |
â Key Takeaways:
- All primary operations run in constant time O(1)
- Array-based: Fixed size, potential space waste, may throw exceptions when full
- Linked List-based: Dynamic size, more memory overhead per element
- Space complexity is O(n) where n is number of elements
Stack vs Queue Comparison
Stack (LIFO)
- Order: Last In, First Out
- Access: One end (top only)
- Operations: push, pop, top
- Use Cases: Undo, recursion, parsing
- Analogy: Stack of plates
Queue (FIFO)
- Order: First In, First Out
- Access: Two ends (front & rear)
- Operations: enqueue, dequeue, first
- Use Cases: Scheduling, BFS, buffering
- Analogy: Waiting line
đ Study Summary
Essential Concepts to Remember
Stack Essentials:
- LIFO principle - last in, first out
- Main operations: push(add), pop(remove), top(peek)
- All operations are O(1) constant time
- Array implementation uses index variable for top
- Used for: undo operations, expression evaluation, recursive algorithms
Queue Essentials:
- FIFO principle - first in, first out
- Main operations: enqueue(add to rear), dequeue(remove from front), first(peek)
- All operations are O(1) constant time
- Array implementation uses circular buffer with modulo arithmetic
- Used for: scheduling, BFS, resource sharing, buffering
đ Exam Tips
- Understand the difference between LIFO and FIFO
- Be able to trace through push/pop and enqueue/dequeue operations
- Know the time complexity of all operations (O(1))
- Understand circular queue implementation with modulo
- Be familiar with practical applications of each structure
- Practice parentheses matching and expression evaluation
- Know when to use a stack vs. a queue