Skip to content

Instantly share code, notes, and snippets.

@xcaptain
Created August 7, 2018 03:52
Show Gist options
  • Save xcaptain/3bc26ad820ce55242b7edf04a43fbf30 to your computer and use it in GitHub Desktop.
Save xcaptain/3bc26ad820ce55242b7edf04a43fbf30 to your computer and use it in GitHub Desktop.
simple list implementation in rust
struct List {
head: Link,
}
type Link = Option<Box<Node>>;
struct Node {
elem: i32,
next: Link,
}
impl List {
fn new() -> Self {
return List {
head: None
};
}
fn push(&mut self, elem: i32) {
let new_node = Box::new(Node {
elem: elem,
next: self.head.take(),
});
self.head = Some(new_node);
}
fn pop(&mut self) -> Option<i32> {
match self.head.take() {
None => None,
Some(node) => {
let node = *node;
self.head = node.next;
Some(node.elem)
}
}
}
}
impl Drop for List {
fn drop(&mut self) {
let mut cur_link = self.head.take();
// 从box中解出node本身,把指针清空,避免递归的清空资源
while let Some(mut boxed_node) = cur_link {
cur_link = boxed_node.next.take();
}
}
}
fn main() {
let mut l = List::new();
l.push(1);
l.push(2);
l.push(3);
let a = l.pop().unwrap();
println!("elem: {}", a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment