Newer
Older
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
use crate::Stack;
// TODO Complete implementation
impl Stack for Vec<i32> {
fn init() -> Self {
todo!()
}
fn push_val(&mut self, i: i32) {
todo!()
}
fn top_val(&self) -> Option<&i32> {
todo!()
}
fn pop_val(&mut self) -> Option<i32> {
todo!()
}
fn is_empty(&self) -> bool {
todo!()
}
}
#[derive(Debug)]
pub enum ListStack {
Val(i32, Option<Box<ListStack>>),
Nil,
}
use ListStack::Nil;
use ListStack::Val;
// Complete implementation of Stack for ListStack
impl Stack for ListStack {
fn init() -> Self {
Nil
}
fn push_val(&mut self, i: i32) {
match self {
Val(value, other) => *self = todo!(),
Nil => *self = todo!(),
};
}
fn top_val(&self) -> Option<&i32> {
todo!()
}
fn pop_val(&mut self) -> Option<i32> {
match self {
Val(value, other) => {
let popped_value = *value;
match other.take() {
None => *self = Nil,
Some(other) => todo!(),
};
todo!()
}
Nil => None,
}
}
fn is_empty(&self) -> bool {
todo!()
}
}
#[cfg(test)]
mod tests {
use crate::stack::ListStack;
use crate::Stack;
use std::fmt::Debug;
#[test]
fn vec_fill_and_clear() {
println! {"Testing Vec<T>"}
fill_and_clear_impl(Vec::init());
}
#[test]
fn linked_fill_and_clear() {
println! {"Testing ListStack"}
fill_and_clear_impl(ListStack::init());
}
fn fill_and_clear_impl<T: Stack + Debug>(mut stack: T) {
stack.push_val(1);
assert_eq!(stack.top_val(), Some(&1));
stack.push_val(2);
assert_eq!(stack.top_val(), Some(&2));
stack.push_val(-3);
assert_eq!(stack.top_val(), Some(&-3));
println!("{:?}", stack);
let mut comparison = vec![1, 2, -3];
while let Some(val) = stack.pop_val() {
assert_eq!(comparison.pop().unwrap(), val);
}
assert!(stack.is_empty())
}
}