Complete the code to create a new empty queue.
fn new() -> Self {
Queue { front: None, rear: None, size: [1] }
}The queue starts empty, so size should be 0.
Complete the code to add a new node at the rear of the queue.
fn enqueue(&mut self, value: i32) {
let new_node = Box::new(Node { data: value, next: None });
if self.rear.is_none() {
self.front = Some(new_node);
self.rear = Some(new_node);
} else {
self.rear.as_mut().unwrap().next = Some(new_node);
self.rear = [1];
}
self.size += 1;
}After linking the new node, rear should point to the new node, which is the next of the old rear. Since rear is an Option
Fix the error in the dequeue method to correctly remove the front node.
fn dequeue(&mut self) -> Option<i32> {
match self.front.take() {
None => None,
Some(node) => {
self.front = [1];
if self.front.is_none() {
self.rear = None;
}
self.size -= 1;
Some(node.data)
}
}
}After removing the front node, front should point to the next node of the removed node.
Fill both blanks to implement a method that checks if the queue is empty.
fn is_empty(&self) -> bool {
self.size [1] 0 && self.front [2] None
}The queue is empty if size equals zero and front is None.
Fill all three blanks to implement a method that returns the front value without removing it.
fn peek(&self) -> Option<i32> {
match &self.front {
Some(node) => Some(node.[1]),
None => [2],
}
}Peek returns the data of the front node if it exists, otherwise None.
