Module 4Stack, Queue & DequeLesson 15 of 2318 min
Stack with Vec
push/pop back; valid parentheses; monotonic stack intro.
Stack = Vec
rust
fn main() {
let mut st = Vec::new();
st.push(1);
st.push(2);
st.push(3);
println!("peek={:?}", st.last());
println!("pop={:?}", st.pop());
println!("stack={st:?}");
}Output
peek=Some(3)
pop=Some(3)
stack=[1, 2]Valid parentheses
Push openers; on closer, pop and match.
Monotonic stack (preview)
Keep increasing/decreasing stack of indices for next greater element — O(n).
Challenge
Next greater element: for each nums[i], find first greater to the right (-1 if none).
Tips
- last() peeks
- pop returns Option
- Empty stack edge cases
Try it live
Stack with VecRust 2021
Loading editor…
Output
Press Run to compile and execute.