Welcome to an exploration of two foundational data structures: Stacks and Queues! These structures are essential for organizing data in a structured, efficient manner. Imagine a stack like a pile of plates, where the last plate added is the first to be removed (LIFO). In contrast, a queue is like a line at the store, where the first person in line is served first (FIFO). Let’s dive in and see how these structures work in Ruby!
A stack follows the LIFO (Last In, First Out) principle. Think of a stack as a pile of plates — the last plate added is the first to be removed. In Ruby, arrays make a convenient base for stacks, using push
to add items and pop
to remove them.
Here’s a simple example using a stack of plates:
In this example, the last plate added (Plate 2) is the first one removed, demonstrating the LIFO behavior of a stack.
A queue follows the FIFO (First In, First Out) principle, much like waiting in line. Ruby arrays can also represent queues, where push
adds an item to the end, and shift
removes the item from the front.
Here’s an example of a queue of people:
Here, Person 1, the first to enter the queue, is also the first to leave, showcasing the FIFO behavior of a queue.
- Stacks are ideal for managing ordered tasks, such as:
- Undo/Redo Systems: In text editors, the last action (e.g., inserting text) is undone first.
- Call Stack in Recursion: Tracks function calls, with the most recent call resolved first.
- Expression Evaluation: Used to evaluate postfix or infix expressions.
- Web Browser History: Navigates back to the most recent page visited.
- Queues are great when the order of arrival is important, like:
- Task Scheduling: Ensures tasks are processed in the order they arrive (e.g., print jobs).
- Breadth-First Search (BFS): Utilizes a queue to explore nodes level by level.
- Event Queues: Processes events in systems like GUI applications.
- Customer Service Lines: Serves customers in the order they arrive.
Let’s combine both structures in a realistic scenario: a text editor with an Undo feature (stack) and a Print Queue (queue).
In this example:
- The stack (
@stack
) holds changes to be undone, with the last change made being the first to undo. - The queue (
@queue
) manages print jobs in the order they’re added, with the first document queued being the first to print.
Great job! You’ve covered the essentials of stacks and queues, two critical data structures in programming. Stacks follow the LIFO principle, perfect for tasks like undo actions, while queues follow FIFO, ideal for tasks like print job management. Keep practicing to reinforce these concepts — happy coding!
