Solving problems using queues and deques
Now that we know how to use the Queue
and Deque
classes, let's use them to solve some computer science problems. In this section, we will cover a simulation of the Hot Potato game with queues and how to check whether a phrase is a palindrome with deques.
The circular queue: the Hot Potato game
The Hot Potato game is a classic children's game where participants form a circle and pass around an object (the "hot potato") as fast as they can while music plays. When the music stops, the person holding the potato is eliminated. The game continues until only one person remains.
The CircularQueue class
We can perfectly simulate this game using a Circular Queue implementation:
class CircularQueue {
#items = [];
#capacity = 0; // {1}
#front = 0; // {2}
#rear = -1; // {3}
#size = 0; // {4}
constructor(capacity) { // {5}
this.#items = new Array(capacity);
this.#capacity = capacity;
}
get size() { return this....