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();
}
}
}