-
Notifications
You must be signed in to change notification settings - Fork 0
/
array_stack.rs
49 lines (45 loc) · 1.05 KB
/
array_stack.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use super::*;
pub struct ArrayStack<T> {
// If this is Box<[T]>, new() can't initialize `None`
array: Box<[Option<T>]>,
len: usize,
}
impl<T: Clone> ArrayStack<T> {
pub fn new(n: usize) -> Self {
Self {
array: vec![None; n].into_boxed_slice(),
len: 0,
}
}
}
impl<T: Clone> Stack<T> for ArrayStack<T> {
fn len(&self) -> usize {
self.len
}
fn is_empty(&self) -> bool {
self.len() == 0
}
fn get(&self, i: usize) -> T {
self.array.get(i).unwrap().clone().unwrap()
}
fn push(&mut self, x: T) {
*self.array.get_mut(self.len).unwrap() = Some(x);
self.len += 1;
}
fn pop(&mut self) -> T {
self.len -= 1;
self.array.get(self.len).unwrap().clone().unwrap()
}
}
#[test]
fn test() {
let mut stack = ArrayStack::new(10);
stack.push(0);
stack.push(1);
stack.push(2);
assert_eq!(stack.pop(), 2);
assert_eq!(stack.pop(), 1);
assert_eq!(stack.pop(), 0);
stack.push(3);
assert_eq!(stack.pop(), 3);
}