I wanted to implement a stack, but I am having a lot of trouble with pop. I'm trying to do it with a while let loop, but can't seem to beat the borrow checker.
pub struct Stack<T>{
top: Option<Box<Node<T>>>,
}
struct Node<T>{
val: T,
under: Option<Box<Node<T>>>,
}
Here's the Stack implementation and here is pop:
pub fn pop(&mut self) -> Option<T>{
if self.top.is_none(){
return None;
}
let mut last_node = &mut self.top;
while let Some(node) = last_node{
if node.under.is_none(){
break;
} else{
last_node = &mut node.under;
}
}
let return_node = std::mem::replace(last_node, None);
return Some(return_node.unwrap().val);
}