Stacks and Queues
Queue Enqueue/Dequeue
Enqueue values at the back and dequeue them from the front in first-in, first-out order.
Algorithm
Basic Implementation
basic.rs
use std::collections::VecDeque;
fn render(values: &[i32]) -> String {
values.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(" -> ")
}
fn main() {
let mut queue = VecDeque::new();
for value in [10, 20, 30] { queue.push_back(value); }
let mut removed = Vec::new();
while let Some(value) = queue.pop_front() { removed.push(value); }
println!("{}", render(&removed));
}
Complexity
- Time: O(1) per operation with a real queue
- Space: O(n)
Implementation notes
- The checked source imports
std::collections::VecDequeand createslet mut queue = VecDeque::new()for the FIFO queue. - Enqueue uses
queue.push_back(value)for ownedi32values from the fixed array literal[10, 20, 30]. - Dequeue uses
while let Some(value) = queue.pop_front().pop_frontreturnsOption<i32>;Some(value)moves the integer into the loop body, andNoneends the loop without a separate empty check. - Removed values are collected in
let mut removed = Vec::new()withremoved.push(value). - The trace records
queue=[], enqueue to[10, 20, 30], one front removal toremoved=[10]withqueue=[20, 30], then draining toremoved=[10, 20, 30]andqueue=[]. render(&removed)borrows the result slice, maps each integer throughto_string(), joins with" -> ", andprintln!("{}", ...)prints10 -> 20 -> 30.
front
The front is the oldest value still waiting in the queue.
FIFO
A queue removes values in first-in, first-out order.