Complete the code to initialize the front index of the circular queue.
struct CircularQueue {
front: i32,
rear: i32,
size: usize,
data: Vec<i32>,
}
impl CircularQueue {
fn new(capacity: usize) -> Self {
CircularQueue {
front: [1],
rear: -1,
size: capacity,
data: vec![0; capacity],
}
}
}The front index is initialized to -1 to indicate the queue is empty initially.
Complete the code to check if the circular queue is full.
impl CircularQueue {
fn is_full(&self) -> bool {
(self.rear + 1) % (self.size as i32) == [1]
}
}The queue is full when the next position of rear equals front.
Fix the error in the enqueue method to correctly update the rear index.
impl CircularQueue {
fn enqueue(&mut self, value: i32) -> Result<(), &str> {
if self.is_full() {
return Err("Queue is full");
}
self.rear = [1];
self.data[self.rear as usize] = value;
if self.front == -1 {
self.front = 0;
}
Ok(())
}
}The rear index must wrap around using modulo to stay within array bounds.
Fill both blanks to correctly update the front index in the dequeue method and handle empty queue.
impl CircularQueue {
fn dequeue(&mut self) -> Result<i32, &str> {
if self.front == -1 {
return Err("Queue is empty");
}
let value = self.data[self.front as usize];
if self.front == self.rear {
self.front = [1];
self.rear = [2];
} else {
self.front = (self.front + 1) % (self.size as i32);
}
Ok(value)
}
}When the last element is dequeued, both front and rear reset to -1 to mark empty queue.
Fill all three blanks to implement the display method that prints queue elements in order.
impl CircularQueue {
fn display(&self) {
if self.front == -1 {
println!("Queue is empty");
return;
}
let mut i = self.front;
loop {
print!("{} ", self.data[i as usize]);
if i == self.rear {
break;
}
i = (i + [1]) % (self.size as i32);
}
println!();
}
}Increment index by 1 modulo size to traverse queue elements circularly.
