1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use std::rc::Rc;

#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct Node<T> {
    val: T,
    next: Option<Rc<Node<T>>>,
}

/// A persistent stack.
///
/// This is similar to `Stack` from the rpds crate, but it's faster
/// and uses less memory.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Stack<T> {
    head: Option<Rc<Node<T>>>,
}

impl<T> Stack<T> {
    pub(crate) fn new() -> Self {
        Self { head: None }
    }

    pub(crate) fn peek(&self) -> Option<&T> {
        self.head.as_deref().map(|n| &n.val)
    }

    pub(crate) fn pop(&self) -> Option<Stack<T>> {
        self.head.as_deref().map(|n| Self {
            head: n.next.clone(),
        })
    }

    pub(crate) fn push(&self, v: T) -> Stack<T> {
        Self {
            head: Some(Rc::new(Node {
                val: v,
                next: self.head.clone(),
            })),
        }
    }

    // O(n)
    pub(crate) fn size(&self) -> usize {
        let mut count = 0;
        let mut node = &self.head;
        while let Some(next) = node {
            count += 1;
            node = &next.next;
        }
        count
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.head.is_none()
    }
}