use std::fmt::{self, Debug};
#[derive(Clone)]
pub struct Stack<T> {
head: Option<Box<Node<T>>>,
size: usize,
}
impl<T> Stack<T> {
pub fn new() -> Self {
Self {
head: None,
size: 0,
}
}
pub fn push(&mut self, val: T) {
self.size += 1;
self.head = Some(Box::new(Node {
val,
next: self.head.take(),
}));
}
pub fn pop(&mut self) -> Option<T> {
self.head.take().map(|head| {
self.size -= 1; self.head = head.next;
head.val
})
}
pub fn peek(&self) -> Option<&T> {
self.head.as_ref().map(|head| &head.val)
}
pub fn peek_mut(&mut self) -> Option<&mut T> {
self.head.as_mut().map(|head| &mut head.val)
}
pub fn size(&self) -> usize {
self.size
}
}
impl<T> Default for Stack<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> Debug for Stack<T>
where
T: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut vec = Vec::with_capacity(self.size);
let mut cur_node = &self.head;
while let Some(node) = cur_node {
vec.push(&node.val);
cur_node = &node.next;
}
vec.reverse();
f.debug_list().entries(vec).finish()
}
}
#[derive(Clone)]
struct Node<T> {
val: T,
next: Option<Box<Node<T>>>,
}