algo_rs/data_structure/stack/
growable_stack.rs

1use crate::data_structure::stack::Stack;
2
3pub struct GrowableStack<T> {
4    inner: Vec<T>,
5}
6
7impl<T> GrowableStack<T> {
8    pub fn new() -> Self {
9        Self {
10            inner: Vec::<T>::new(),
11        }
12    }
13
14    pub fn with_capacity(size: usize) -> Self {
15        Self {
16            inner: Vec::<T>::with_capacity(size),
17        }
18    }
19}
20
21impl<T> Stack<T> for GrowableStack<T> {
22    fn push(&mut self, item: T) {
23        self.inner.push(item)
24    }
25
26    fn pop(&mut self) -> Option<T> {
27        self.inner.pop()
28    }
29
30    fn top(&self) -> Option<&T> {
31        self.inner.last()
32    }
33
34    fn is_empty(&self) -> bool {
35        self.inner.is_empty()
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use crate::data_structure::stack::growable_stack::GrowableStack;
42    use crate::data_structure::stack::Stack;
43
44    #[test]
45    fn test_push_pop() {
46        let mut stack = GrowableStack::<i32>::new();
47        stack.push(1);
48        stack.push(2);
49        stack.push(3);
50        assert_eq!(Some(3), stack.pop());
51        assert_eq!(Some(2), stack.pop());
52        assert_eq!(Some(1), stack.pop());
53        assert_eq!(None, stack.pop());
54    }
55
56    #[test]
57    fn test_is_empty() {
58        let mut stack = GrowableStack::<i32>::new();
59        assert_eq!(true, stack.is_empty());
60        stack.push(1);
61        assert_eq!(false, stack.is_empty());
62        stack.pop();
63        assert_eq!(true, stack.is_empty());
64    }
65
66    #[test]
67    fn test_top() {
68        let mut stack = GrowableStack::<i32>::new();
69        assert_eq!(None, stack.top());
70        stack.push(1);
71        assert_eq!(Some(&1), stack.top());
72        stack.push(2);
73        assert_eq!(Some(&2), stack.top());
74        stack.pop();
75        assert_eq!(Some(&1), stack.top());
76        stack.pop();
77        assert_eq!(None, stack.top());
78    }
79}