Compare commits
No commits in common. "534b0d39e04e4756a76f7970d4af64a7c1dbfdce" and "95998d4a95bdea7c5ca4d34d079335844d6b4bbf" have entirely different histories.
534b0d39e0
...
95998d4a95
2 changed files with 16 additions and 39 deletions
|
|
@ -1 +0,0 @@
|
||||||
simple implementation of linkedlist for rust workshop, with tags on every commit
|
|
||||||
54
src/main.rs
54
src/main.rs
|
|
@ -1,56 +1,34 @@
|
||||||
fn main() {
|
fn main() {}
|
||||||
let mut list = List::new();
|
|
||||||
list.push(1);
|
#[derive(Debug)]
|
||||||
println!("push(1) : {:?}", list);
|
pub struct List {
|
||||||
list.push(2);
|
head: Link,
|
||||||
println!("push(2) : {:?}", list);
|
|
||||||
println!("pop() -> {} : {:?}", list.pop().unwrap(), list);
|
|
||||||
println!("pop() -> {} : {:?}", list.pop().unwrap(), list);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct List<T> {
|
enum Link {
|
||||||
head: Link<T>,
|
Empty,
|
||||||
|
More(Box<Node>),
|
||||||
}
|
}
|
||||||
|
|
||||||
type Link<T> = Option<Box<Node<T>>>;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct Node<T> {
|
struct Node {
|
||||||
elem: T,
|
elem: i32,
|
||||||
next: Link<T>,
|
next: Link,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> List<T> {
|
impl List {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self { head: None }
|
Self { head: Link::Empty }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn push(&mut self, elem: T) {
|
pub fn push(&mut self, elem: i32) {
|
||||||
let new_node = Node {
|
let new_node = Node {
|
||||||
elem: elem,
|
elem: elem,
|
||||||
next: self.head.take(),
|
next: std::mem::replace(&mut self.head, Link::Empty),
|
||||||
};
|
};
|
||||||
self.head = Some(Box::new(new_node));
|
self.head = Link::More(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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue