Newer
Older
// TODO Complete implementation
impl Stack for Vec<i32> {
fn init() -> Self {
/*either dereference self or access last reference to last element and check if empty */
if (*self).is_empty(){
None
}else{
// returns reference of last element of vec
Some(&self[self.len()-1])
}
}
}
#[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) {
//mem:replace notwendig da liststack keinen copytrait hat und wir so nicht ownership wechseln koennen
Val(value, other) => *self = Val(i,Some(Box::new(std::mem::replace(self, Nil)))),
//zeigt urspruenglich auf nil => fuege ein und mache restliste zu nil
Nil => *self = Val(i,None),
match self{
Nil => None,
Val(value, other) => Some(value),
}
}
fn pop_val(&mut self) -> Option<i32> {
match self {
Val(value, other) => {
let popped_value = *value;
match other.take() {
None => *self = Nil,
//some(other) also findet die box<liststack> also box pointer/reference auf liststack. *other zum dereference
Some(other) => *self = *other ,
}
Nil => None,
}
}
fn is_empty(&self) -> bool {
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
}
}
#[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())