1pub struct Queue<T> {
2 head: Option<Box<Node<T>>>,
3 tail: Option<*mut Node<T>>,
4}
5
6pub trait TQueue<T> {
7 fn new() -> Self;
8 fn enqueue(&mut self, item: T);
9 fn dequeue(&mut self) -> Option<T>;
10 fn len(&self) -> usize;
11 fn front(&self) -> Option<&T>;
12 fn is_empty(&self) -> bool;
13}
14
15struct Node<T> {
16 value: T,
17 next: Option<Box<Node<T>>>,
18}
19
20impl<T> Queue<T> {
21 pub fn new() -> Self {
22 return Queue {
23 tail: None,
24 head: None,
25 };
26 }
27
28 pub fn enqueue(&mut self, item: T) {
29 let new_node = Box::new(Node {
30 value: item,
31 next: None,
32 });
33
34 let raw_node = Box::into_raw(new_node);
35
36 if let Some(tail) = self.tail {
37 unsafe {
38 (*tail).next = Some(Box::from_raw(raw_node));
39 }
40 } else {
41 self.head = unsafe { Some(Box::from_raw(raw_node)) }
42 }
43
44 self.tail = Some(raw_node);
45 }
46
47 pub fn dequeue(&mut self) -> Option<T> {
48 return self.head.take().map(|head| {
49 self.head = head.next;
50
51 if self.head.is_none() {
52 self.tail = None;
53 }
54
55 head.value
56 });
57 }
58
59 pub fn len(&self) -> usize {
60 let mut counter = 0;
61 let mut current_node = &self.head;
62
63 while let Some(node) = current_node {
64 counter += 1;
65 current_node = &node.next;
66 }
67
68 return counter;
69 }
70
71 pub fn front(&self) -> Option<&T> {
72 return self.head.as_ref().map(|node| &node.value);
73 }
74
75 pub fn is_empty(&self) -> bool {
76 return self.head.is_none();
77 }
78}