Complete the code to initialize the front pointer of the circular queue.
class CircularQueue { private front: number = [1]; private rear: number = -1; private size: number; private queue: number[]; constructor(size: number) { this.size = size; this.queue = new Array(size); } }
The front pointer starts at -1 (same as rear) to indicate the empty queue.
Complete the code to check if the circular queue is full.
isFull(): boolean {
return (this.rear + 1) % this.size === [1];
}The queue is full when the next position of rear wraps around to front.
Fix the error in the enqueue method to correctly update the rear pointer.
enqueue(value: number): void {
if (this.isFull()) {
throw new Error('Queue is full');
}
this.rear = (this.rear [1] 1) % this.size;
this.queue[this.rear] = value;
}To move rear forward by one position circularly, add 1 and take modulo size.
Fill both blanks to correctly update the front pointer in the dequeue method and return the dequeued value.
dequeue(): number {
if (this.front === -1) {
throw new Error('Queue is empty');
}
const value = this.queue[this.front];
if (this.front === this.rear) {
this.front = [1];
this.rear = [2];
} else {
this.front = (this.front + 1) % this.size;
}
return value;
}When the last element is dequeued, both front and rear are reset to -1 to indicate empty queue.
Fill both blanks to implement the peek method that returns the front element without removing it.
peek(): number {
if (this.front === [1]) {
throw new Error('Queue is empty');
}
return this.queue[[2]];
}Peek checks if front is -1 (empty), then returns the element at front index.
