Stacks and Queues
Stack Push/Pop
Push values onto a stack and pop them back in last-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 stack = Vec::new();
for value in [10, 20, 30] { stack.push(value); }
let mut popped = Vec::new();
while let Some(value) = stack.pop() { popped.push(value); }
println!("{}", render(&popped));
}
Complexity
- Time: O(1) per push/pop
- Space: O(n)
Implementation notes
- The checked source imports
VecDeque, but the stack itself islet mut stack = Vec::new(), a mutableVec<i32>. - Pushes use
stack.push(value)for ownedi32values from[10, 20, 30], leaving the top of the stack at the vector's end. - Pops use
while let Some(value) = stack.pop().Vec::popreturnsOption<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 popped = Vec::new()withpopped.push(value), preserving the observed pop order. - The trace records
stack=[], push to[10, 20, 30], first pop topopped=[30]withstack=[10, 20], then draining topopped=[30, 20, 10]andstack=[]. render(&popped)borrows the result slice, converts each integer withto_string(), joins with" -> ", andprintln!("{}", ...)prints30 -> 20 -> 10.
top
The top is the most recently pushed value.
LIFO
A stack removes values in last-in, first-out order.