📝
too-many-list-zh
  • 目录
  • 介绍
  • 一个糟糕的单链栈
    • 布局
    • New
    • 所有权
    • Push
    • Pop
    • 测试
    • Drop
    • 最终代码
  • 一个还行的单链栈
    • Option
    • Generic
    • Peek
    • IntoIter
    • Iter
    • IterMut
    • 最终代码
  • 一个不可变栈
    • 布局
    • 基础
    • Drop
    • Arc
    • 最终代码
  • 一个糟糕但安全的双向队列
    • 布局
    • 构建
    • 任务分解
    • Peek
    • 对称情况
    • Iteration
    • 最终代码
  • 一个不安全的队列
    • 布局
    • UnSafe
    • 基础
    • 拓展
    • 最终代码
  • 一个还行不安全双向队列
  • 一堆无聊的清单
    • 双重单链表
Powered by GitBook
On this page

Was this helpful?

  1. 一个糟糕的单链栈

最终代码

好吧,6000字之后,这是我们实际编写的所有代码:

use std::mem;

pub struct List {
    head: Link,
}

enum Link {
    Empty,
    More(Box<Node>),
}

struct Node {
    elem: i32,
    next: Link,
}

impl List {
    pub fn new() -> Self {
        List { head: Link::Empty }
    }

    pub fn push(&mut self, elem: i32) {
        let new_node = Box::new(Node {
            elem: elem,
            next: mem::replace(&mut self.head, Link::Empty),
        });

        self.head = Link::More(new_node);
    }

    pub fn pop(&mut self) -> Option<i32> {
        match mem::replace(&mut self.head, Link::Empty) {
            Link::Empty => None,
            Link::More(node) => {
                self.head = node.next;
                Some(node.elem)
            }
        }
    }
}

impl Drop for List {
    fn drop(&mut self) {
        let mut cur_link = mem::replace(&mut self.head, Link::Empty);

        while let Link::More(mut boxed_node) = cur_link {
            cur_link = mem::replace(&mut boxed_node.next, Link::Empty);
        }
    }
}

#[cfg(test)]
mod test {
    use super::List;

    #[test]
    fn basics() {
        let mut list = List::new();

        // Check empty list behaves right
        assert_eq!(list.pop(), None);

        // Populate list
        list.push(1);
        list.push(2);
        list.push(3);

        // Check normal removal
        assert_eq!(list.pop(), Some(3));
        assert_eq!(list.pop(), Some(2));

        // Push some more just to make sure nothing's corrupted
        list.push(4);
        list.push(5);

        // Check normal removal
        assert_eq!(list.pop(), Some(5));
        assert_eq!(list.pop(), Some(4));

        // Check exhaustion
        assert_eq!(list.pop(), Some(1));
        assert_eq!(list.pop(), None);
    }
}

天哪。80行,其中一半是测试!好吧,我说过第一个需要一段时间!

PreviousDropNext一个还行的单链栈

Last updated 4 years ago

Was this helpful?