Created
January 6, 2017 13:25
-
-
Save topecongiro/f59e089e7fc6104e82896bd299b73300 to your computer and use it in GitHub Desktop.
A simple stack in Rust using Option and Box.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Node<T> { | |
val: T, | |
next: Option<Box<Node<T>>>, | |
} | |
pub struct Stack<T> { | |
top: Option<Box<Node<T>>>, | |
} | |
impl <T>Stack<T> { | |
pub fn new() -> Stack<T> { | |
Stack { | |
top: None, | |
} | |
} | |
pub fn push(&mut self, val: T) { | |
self.top = Some(Box::new(Node { | |
val: val, | |
next: self.top.take(), | |
})) | |
} | |
pub fn pop(&mut self) { | |
match self.top.take() { | |
None => return, | |
Some(mut node_box) => self.top = (*node_box).next.take(), | |
} | |
} | |
pub fn top(&self) -> &T { | |
match &self.top { | |
&None => panic!(), | |
&Some(ref node_box) => &(*node_box).val, | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment