Queue & Stack Patterns
Queues and stacks are fundamental data structures that follow specific access patterns. Queues use FIFO (First In, First Out) while stacks use LIFO (Last In, First Out). Ruby provides built-in Queue class and you can implement stacks using arrays.
Queue (FIFO) - First In, First Out
Queue: A queue follows FIFO (First In, First Out) principle. Elements are added to the rear and removed from the front. Perfect for task processing, breadth-first search, and maintaining order.
Ruby's Built-in Queue Class
Array-based Queue Implementation
Stack (LIFO) - Last In, First Out
Stack: A stack follows LIFO (Last In, First Out) principle. Elements are added and removed from the same end (top). Perfect for function calls, undo operations, and depth-first search.
Array-based Stack Implementation
Custom Stack Class
Practical Applications
Queue Applications
Stack Applications
Interactive Practice: Queue & Stack Patterns
Practice Time: Try these queue and stack examples and experiment with different FIFO/LIFO patterns. Understanding these data structures will make you a more effective Ruby programmer.
Interactive Code Runner
Ruby Code Editor
Queue & Stack Best Practices
✅ Do This
- Use Queue for thread-safe operations
- Use arrays for simple queue/stack implementations
- Implement proper error handling for empty structures
- Use queues for task processing and BFS
- Use stacks for undo/redo and DFS
❌ Avoid This
- Using wrong data structure for the problem
- Not handling empty queue/stack cases
- Using Queue when thread safety isn't needed
- Forgetting FIFO vs LIFO principles
- Not considering performance implications
Queue & Stack Mastery Checklist
- Queue (FIFO): Understand First In, First Out principle
- Stack (LIFO): Understand Last In, First Out principle
- Built-in Queue: Use Ruby's thread-safe Queue class
- Array Implementation: Implement queues and stacks with arrays
- Operations: Master enqueue/dequeue and push/pop operations
- Applications: Apply to task processing, undo/redo, and algorithms
- Error Handling: Handle empty queue/stack cases properly
- Performance: Understand time and space complexity
Next Steps: Practice with queues for task processing and stacks for undo operations. These fundamental data structures are essential for many algorithms and real-world applications!