first-rust/src/stack.rs
2024-11-22 15:43:02 -06:00

44 lines
827 B
Rust

pub struct Stack<T> {
head: Link<T>,
}
enum Link<T> {
Empty,
More(Box<Node<T>>),
}
struct Node<T> {
data: T,
next: Link<T>,
}
impl<T> Stack<T> {
pub fn new() -> Self {
Stack { head: Link::Empty }
}
pub fn push(&mut self, data: T) {
self.head = Link::More(Box::new(Node {
data,
next: std::mem::replace(&mut self.head, Link::Empty),
}));
}
pub fn pop(&mut self) -> Option<T> {
match std::mem::replace(&mut self.head, Link::Empty) {
Link::Empty => None,
Link::More(node) => {
self.head = node.next;
Some(node.data)
}
}
}
}
impl<T> Iterator for Stack<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.pop()
}
}