use crate::data_structure::stack::Stack;
pub struct GrowableStack<T> {
inner: Vec<T>,
}
impl<T> GrowableStack<T> {
pub fn new() -> Self {
Self {
inner: Vec::<T>::new(),
}
}
pub fn with_capacity(size: usize) -> Self {
Self {
inner: Vec::<T>::with_capacity(size),
}
}
}
impl<T> Stack<T> for GrowableStack<T> {
fn push(&mut self, item: T) {
self.inner.push(item)
}
fn pop(&mut self) -> Option<T> {
self.inner.pop()
}
fn top(&self) -> Option<&T> {
self.inner.last()
}
fn is_empty(&self) -> bool {
self.inner.is_empty()
}
}
#[cfg(test)]
mod tests {
use crate::data_structure::stack::growable_stack::GrowableStack;
use crate::data_structure::stack::Stack;
#[test]
fn test_push_pop() {
let mut stack = GrowableStack::<i32>::new();
stack.push(1);
stack.push(2);
stack.push(3);
assert_eq!(Some(3), stack.pop());
assert_eq!(Some(2), stack.pop());
assert_eq!(Some(1), stack.pop());
assert_eq!(None, stack.pop());
}
#[test]
fn test_is_empty() {
let mut stack = GrowableStack::<i32>::new();
assert_eq!(true, stack.is_empty());
stack.push(1);
assert_eq!(false, stack.is_empty());
stack.pop();
assert_eq!(true, stack.is_empty());
}
#[test]
fn test_top() {
let mut stack = GrowableStack::<i32>::new();
assert_eq!(None, stack.top());
stack.push(1);
assert_eq!(Some(&1), stack.top());
stack.push(2);
assert_eq!(Some(&2), stack.top());
stack.pop();
assert_eq!(Some(&1), stack.top());
stack.pop();
assert_eq!(None, stack.top());
}
}