Stacks & Queues: LIFO vs. FIFO (Python, Rust)
Let’s explain the association of stacks with LIFO (Last-In-First-Out) and queues with FIFO (First-In-First-Out)
Stacks and LIFO
- Concept: A stack is like a stack of plates. When you add (push) a new plate to the stack, it goes on top. When you remove (pop) a plate, you take it from the top.
- LIFO Principle: The last plate (or item) you placed on the stack will be the first one you remove. This behavior aligns with the Last-In-First-Out principle.
- Example: If you push the numbers 1, 2, and 3 onto a stack in that order, the first number you’d pop off would be 3, then 2, and finally 1.
Queues and FIFO
- Concept: A queue is like a line of people waiting for a bus. The first person to arrive waits at the front, and any subsequent arrivals join the end of the line.
- FIFO Principle: The first person (or item) to join the queue will be the first to leave. This behavior aligns with the First-In-First-Out principle.
- Example: If you enqueue the numbers 1, 2, and 3 into a queue in that order, the first number you’d dequeue would be 1, then 2, and finally 3.
The terms LIFO and FIFO are essentially ways to describe the order in which elements are added and removed from these data structures. Stacks and queues are fundamental data structures in computer science, and understanding their behaviors is crucial for various applications, from parsing expressions to managing processes in an operating system.
Let’s explore alternative ways to represent stacks and queues in both Python and Rust:
# PYTHON SCRIPT
from collections import deque
# Stack using Lists
stack_list = []
stack_list.append(1) # push 1 using list
top_list = stack_list.pop() # pop using list
# Stack using deque
stack_deque = deque()
stack_deque.append(1) # push 1 using deque
top_deque = stack_deque.pop() # pop using deque
# Queue using deque
queue_deque = deque()
queue_deque.append(1) # enqueue 1 using deque
front_deque = queue_deque.popleft() # dequeue using deque
# Queue using Lists (inefficient for large datasets)
queue_list = []
queue_list.append(1) # enqueue 1 using list
front_list = queue_list.pop(0) # dequeue using list
// RUST SCRIPT
use std::collections::{LinkedList, VecDeque};
fn main() {
// Stack using Vec
let mut stack_vec = Vec::new();
stack_vec.push(1); // push 1 using Vec
let top_vec = stack_vec.pop(); // pop using Vec
// Stack using LinkedList
let mut stack_linked_list = LinkedList::new();
stack_linked_list.push_back(1); // push 1 using LinkedList
let top_linked_list = stack_linked_list.pop_back(); // pop using LinkedList
// Queue using VecDeque
let mut queue_vecdeque = VecDeque::new();
queue_vecdeque.push_back(1); // enqueue 1 using VecDeque
let front_vecdeque = queue_vecdeque.pop_front(); // dequeue using VecDeque
// Queue using LinkedList
let mut queue_linked_list = LinkedList::new();
queue_linked_list.push_back
Subscribe to my newsletter to get access to all the content I’ll be publishing in the future.