Complete the code to push an element onto the stack using a vector.
let mut stack = Vec::new(); stack.[1](10);
The push method adds an element to the end of the vector, which acts like pushing onto a stack.
Complete the code to remove the top element from the stack safely.
let mut stack = vec![1, 2, 3]; let top = stack.[1]();
The pop method removes and returns the last element of the vector, which is the top of the stack.
Fix the error in accessing the top element of the stack without removing it.
let stack = vec![5, 6, 7]; let top = stack.[1]();
The last method returns a reference to the last element without removing it, which is the top of the stack.
Fill both blanks to create a stack abstraction with push and pop methods.
struct Stack<T> {
elements: Vec<T>,
}
impl<T> Stack<T> {
fn push(&mut self, item: T) {
self.elements.[1](item);
}
fn pop(&mut self) -> Option<T> {
self.elements.[2]()
}
}Using push adds an item to the vector, and pop removes the last item, implementing stack behavior.
Fill all three blanks to implement a method that checks if the stack is empty and returns its size.
impl<T> Stack<T> {
fn is_empty(&self) -> bool {
self.elements.[1]()
}
fn size(&self) -> usize {
self.elements.[2]()
}
fn clear(&mut self) {
self.elements.[3]();
}
}is_empty checks if the vector has no elements, len returns the number of elements, and clear removes all elements.
