Compare commits

..

No commits in common. "534b0d39e04e4756a76f7970d4af64a7c1dbfdce" and "95998d4a95bdea7c5ca4d34d079335844d6b4bbf" have entirely different histories.

2 changed files with 16 additions and 39 deletions

View file

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

View file

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