As asked
Implement a generic Stack<T> using a Vec as the backing store. It must have push, pop returning Option<T>, and peek returning Option<&T>. Do not use any external crates.
Sample answer outline
Candidate should write a newtype struct wrapping Vec<T>, implement push via Vec::push, pop via Vec::pop, and peek via self.data.last(). Strong answer also implements Display or Iterator, discusses why peek returns a shared reference tied to the stack's lifetime, and notes that this is functionally equivalent to how std's Vec already works.
Reference implementation (rust)
struct Stack<T> {
data: Vec<T>,
}
impl<T> Stack<T> {
fn new() -> Self { Stack { data: Vec::new() } }
fn push(&mut self, item: T) { todo!() }
fn pop(&mut self) -> Option<T> { todo!() }
fn peek(&self) -> Option<&T> { todo!() }
}Expect these follow-ups
- How would you implement this so it is Send + Sync?
- How would you add a size limit and return an error on overflow?