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.
