VecDeque Pushes And Pops At Both Ends
VecDeque pushes and pops at both ends in constant time, serving queue-style head removal and stack-style tail removal from one structure.
Code
use std::collections::VecDeque;
fn main() {
// 双端队列:两端 push/pop 都是 O(1),比 Vec 的 insert(0, …) 高效
let mut queue: VecDeque<&str> = VecDeque::new();
queue.push_back("middle");
queue.push_front("urgent"); // 队首插队
queue.push_back("last");
println!("{queue:?}");
// 队首出队:任务按进入顺序消费
let head = queue.pop_front();
println!("pop_front: {head:?}");
// 队尾出队:栈式消费
let tail = queue.pop_back();
println!("pop_back: {tail:?}");
// 剩余顺序保持稳定,可按索引访问
println!("front: {:?} back: {:?}", queue.front(), queue.back());
println!("len: {} [0]: {}", queue.len(), queue[0]);
}How it works
main drives the whole sequence: push_back/push_front build the deque, pop_front and pop_back consume it from both ends, and the closing prints confirm what remains via front(), back(), len() and indexing.
Using it
Every mutation answers on its own labeled line — pop_front: Some("urgent") consumes the head, pop_back: Some("last") consumes the tail, and front:/back: report "middle" from both ends.
Key statements
let mut queue: VecDeque<&str> = VecDeque::new();
queue.push_front("urgent"); // 队首插队
queue.push_back("last");
let head = queue.pop_front();
Interactive Tools for This Topic
FAQ
- What does VecDeque Pushes And Pops At Both Ends print when run?
- Invoke the file as-is — the `pop_front:`, `pop_back:`, `front:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.