Compare commits

...

10 commits

Author SHA1 Message Date
Sander Hautvast
534b0d39e0 readme 2022-02-14 13:19:07 +01:00
Sander Hautvast
0cf2b5c247 more idiomatic with closure 2022-02-14 13:05:47 +01:00
Sander Hautvast
beb5272b61 mem::replace -> Option::take 2022-02-14 12:57:41 +01:00
Sander Hautvast
eca0964be5 use Option 2022-02-14 12:56:00 +01:00
Sander Hautvast
71587e810c generics 2022-02-14 12:52:53 +01:00
Sander Hautvast
b892e70bb5 main method 2022-02-14 12:50:23 +01:00
Sander Hautvast
45389910ac more idiomatic 2022-01-26 19:36:28 +01:00
Sander Hautvast
4319534b6b another mem replace 2022-01-26 19:10:02 +01:00
Sander Hautvast
06ce6d7cc3 cannot move 2022-01-26 19:07:26 +01:00
Sander Hautvast
ae2d94d6f8 a test 2022-01-26 19:03:39 +01:00
2 changed files with 39 additions and 16 deletions

1
README.md Normal file
View file

@ -0,0 +1 @@
simple implementation of linkedlist for rust workshop, with tags on every commit

View file

@ -1,34 +1,56 @@
fn main() {} fn main() {
let mut list = List::new();
#[derive(Debug)] list.push(1);
pub struct List { println!("push(1) : {:?}", list);
head: Link, list.push(2);
println!("push(2) : {:?}", list);
println!("pop() -> {} : {:?}", list.pop().unwrap(), list);
println!("pop() -> {} : {:?}", list.pop().unwrap(), list);
} }
#[derive(Debug)] #[derive(Debug)]
enum Link { pub struct List<T> {
Empty, head: Link<T>,
More(Box<Node>),
} }
type Link<T> = Option<Box<Node<T>>>;
#[derive(Debug)] #[derive(Debug)]
struct Node { struct Node<T> {
elem: i32, elem: T,
next: Link, next: Link<T>,
} }
impl List { impl<T> List<T> {
pub fn new() -> Self { pub fn new() -> Self {
Self { head: Link::Empty } Self { head: None }
} }
pub fn push(&mut self, elem: i32) { pub fn push(&mut self, elem: T) {
let new_node = Node { let new_node = Node {
elem: elem, elem: elem,
next: std::mem::replace(&mut self.head, Link::Empty), next: self.head.take(),
}; };
self.head = Link::More(Box::new(new_node)); self.head = Some(Box::new(new_node));
}
pub fn pop(&mut self) -> Option<T> {
self.head.take().map(|node| {
self.head = node.next;
node.elem
})
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
let mut list = List::new();
list.push(42);
assert_eq!(Some(42), list.pop());
}
}