Consider a queue implemented with the following operations in Rust:
let mut queue = VecDeque::new(); queue.push_back(10); queue.push_back(20); queue.push_back(30); queue.pop_front(); queue.push_back(40);
What is the printed state of the queue after these operations?
use std::collections::VecDeque;
fn main() {
let mut queue = VecDeque::new();
queue.push_back(10);
queue.push_back(20);
queue.push_back(30);
queue.pop_front();
queue.push_back(40);
for val in &queue {
print!("{} -> ", val);
}
print!("null\n");
}Remember, queue removes elements from the front (FIFO).
The first element (10) is removed by pop_front(). The remaining elements are 20, 30, then 40 is added at the back.
Choose the property that correctly describes how a queue works.
Think about the order in which people line up in a queue.
A queue follows FIFO: the first element added is the first to be removed.
What error will this Rust code cause when run?
use std::collections::VecDeque;
fn main() {
let mut queue = VecDeque::new();
queue.push_back(1);
queue.push_back(2);
let front = queue.pop_front().unwrap();
let front_again = queue.pop_front().unwrap();
let front_third = queue.pop_front().unwrap();
println!("{}", front_third);
}Check how many elements are in the queue before popping.
After popping twice, the queue is empty. The third pop_front returns None. Calling unwrap() on None causes a runtime panic.
Given this Rust code:
use std::collections::VecDeque;
fn main() {
let mut queue = VecDeque::new();
for i in 1..=5 {
queue.push_back(i);
}
queue.pop_front();
queue.pop_front();
queue.push_back(6);
queue.push_back(7);
for val in &queue {
print!("{} -> ", val);
}
print!("null\n");
}What is printed?
Remember that pop_front removes from the front in FIFO order.
Initially queue has 1 to 5. Two pops remove 1 and 2. Then 6 and 7 are added at the back. Remaining elements are 3,4,5,6,7.
Choose the best reason why BFS uses a queue instead of a stack.
Think about the order BFS visits nodes in a graph.
BFS explores nodes level by level, which requires FIFO order. Queue provides FIFO, stack provides LIFO.
