Consider a stack implemented using a vector in Rust. What will be printed after peeking the top element?
fn main() {
let mut stack = vec![10, 20, 30];
if let Some(top) = stack.last() {
println!("Top element: {}", top);
} else {
println!("Stack is empty");
}
}Remember that the last element in the vector represents the top of the stack.
The last() method returns the last element of the vector, which is the top of the stack. Here, 30 is the last element.
What will be the output of the following Rust code that tries to peek the top element of an empty stack?
fn main() {
let stack: Vec<i32> = Vec::new();
match stack.last() {
Some(top) => println!("Top element: {}", top),
None => println!("Stack is empty"),
}
}Check what last() returns when the vector is empty.
The last() method returns None if the vector is empty, so the code prints "Stack is empty".
Identify the reason for the panic in the following Rust code when peeking the top element of a stack.
fn main() {
let stack = vec![1, 2, 3];
let top = stack.last().unwrap();
println!("Top element: {}", top);
let empty_stack: Vec<i32> = Vec::new();
let top_empty = empty_stack.last().unwrap();
println!("Top element: {}", top_empty);
}Check what unwrap() does when called on None.
The unwrap() method causes a panic if called on None. Since empty_stack.last() returns None, calling unwrap() panics.
Consider a stack implemented using a vector in Rust. What is the time complexity of the peek operation (accessing the top element)?
Think about how vectors store elements and how last() works.
Accessing the last element of a vector is a constant time operation because vectors store elements contiguously and keep track of their length.
Given the following Rust code that performs push and pop operations on a stack, what will be the top element after all operations?
fn main() {
let mut stack = Vec::new();
stack.push(5);
stack.push(10);
stack.pop();
stack.push(20);
stack.push(15);
stack.pop();
if let Some(top) = stack.last() {
println!("Top element: {}", top);
} else {
println!("Stack is empty");
}
}Dry run the push and pop operations step by step.
Operations:
push 5 → [5]
push 10 → [5,10]
pop → [5]
push 20 → [5,20]
push 15 → [5,20,15]
pop → [5,20]
Top element is 20.
