Exploring Stacks and Queues in Ruby
Introduction: Stacks and Queues
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!
Stacks: Last In, First Out (LIFO)
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.
Queues: First In, First Out (FIFO)
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 and Queues: When and Where to Use?
