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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
pub mod dummy_queue {

    pub struct Queue<T> {
        head: Option<Box<Node<T>>>,
        tail: Option<*mut Node<T>>,
    }

    pub trait TQueue<T> {
        fn new() -> Self;
        fn enqueue(&mut self, item: T);
        fn dequeue(&mut self) -> Option<T>;
        fn len(&self) -> usize;
        fn front(&self) -> Option<&T>;
        fn is_empty(&self) -> bool;
    }

    struct Node<T> {
        value: T,
        next: Option<Box<Node<T>>>,
    }

    impl<T> TQueue<T> for Queue<T> {
        fn new() -> Self {
            return Queue {
                tail: None,
                head: None,
            };
        }

        fn enqueue(&mut self, item: T) {
            let new_node = Box::new(Node {
                value: item,
                next: None,
            });

            let raw_node = Box::into_raw(new_node);

            if let Some(tail) = self.tail {
                unsafe {
                    (*tail).next = Some(Box::from_raw(raw_node));
                }
            } else {
                self.head = unsafe { Some(Box::from_raw(raw_node)) }
            }

            self.tail = Some(raw_node);
        }

        fn dequeue(&mut self) -> Option<T> {
            return self.head.take().map(|head| {
                self.head = head.next;

                if self.head.is_none() {
                    self.tail = None;
                }

                head.value
            });
        }

        fn len(&self) -> usize {
            let mut counter = 0;
            let mut current_node = &self.head;

            while let Some(node) = current_node {
                counter += 1;
                current_node = &node.next;
            }

            return counter;
        }

        fn front(&self) -> Option<&T> {
            return self.head.as_ref().map(|node| &node.value);
        }

        fn is_empty(&self) -> bool {
            return self.head.is_none();
        }
    }
}