struct Stack<T> {
items: Vec<T>,
}
impl<T> Stack<T> {
fn new() -> Self {
Stack { items: Vec::new() }
}
fn push(&mut self, item: T) {
self.items.push(item);
}
fn pop(&mut self) -> Option<T> {
self.items.pop()
}
fn peek(&self) -> Option<&T> {
self.items.last()
}
fn is_empty(&self) -> bool {
self.items.is_empty()
}
}
fn main() {
let mut stack = Stack::new();
stack.push("Rust");
stack.push("C");
stack.push("C++");
stack.push("Java");
stack.push("Python");
// Peek at the top element
if let Some(top) = stack.peek() {
println!("Top of stack: {}", top);
}
println!();
println!("{}", stack.is_empty());
println!();
// Pop all elements until the stack is empty
while !stack.is_empty() {
if let Some(word) = stack.pop() {
println!("{}", word);
}
}
}
/*
run:
Top of stack: Python
false
Python
Java
C++
C
Rust
*/