Complete the code to create a new empty Dequeue.
struct Dequeue<T> {
head: Option<Box<Node<T>>>,
tail: Option<*mut Node<T>>,
}
impl<T> Dequeue<T> {
fn new() -> Self {
Dequeue {
head: [1],
tail: None,
}
}
}The Dequeue starts empty, so head should be None.
Complete the code to add a new node at the front of the Dequeue.
fn push_front(&mut self, value: T) {
let mut new_node = Box::new(Node {
value,
next: self.head.take(),
});
let raw_node: *mut _ = &mut *new_node;
self.head = Some(new_node);
if self.tail.is_none() {
self.tail = [1];
}
}When the list was empty, tail should point to the new node's raw pointer.
Fix the error in the code to correctly remove a node from the back of the Dequeue.
fn pop_back(&mut self) -> Option<T> {
if self.head.is_none() {
return None;
}
let mut current = self.head.as_mut().unwrap();
while let Some(ref mut next_node) = current.next {
if next_node.next.is_none() {
let last_value = [1];
current.next = None;
self.tail = Some(current as *mut _);
return Some(last_value);
}
current = next_node;
}
// Single element case
let head = self.head.take().unwrap();
self.tail = None;
Some(head.value)
}We must replace the value to move it out safely. Using Default::default() is safe for generic types.
Fill both blanks to complete the method that checks if the Dequeue is empty.
fn is_empty(&self) -> bool {
self.head [1] None && self.tail [2] None
}The Dequeue is empty if both head and tail are None.
Fill all three blanks to complete the method that adds a node at the back of the Dequeue.
fn push_back(&mut self, value: T) {
let mut new_node = Box::new(Node {
value,
next: None,
});
let raw_node: *mut _ = &mut *new_node;
if self.tail.is_none() {
self.head = Some(new_node);
self.tail = Some(raw_node);
} else {
unsafe {
(*self.tail.unwrap()).[1] = Some(new_node);
}
self.tail = [2];
}
}
// Helper method to get raw pointer from Box
fn get_raw(node: &mut Box<Node<T>>) -> *mut Node<T> {
[3]
}1. Set the next of the current tail to the new node.
2. Update tail to point to the new node's raw pointer.
3. Return raw pointer from the Box by dereferencing.
