Queues
A queue is a data structure that follows the FIFO (first-in, first-out) principle, which means that the first element added to the queue will be the first one to be removed. A queue can be implemented using an array or a linked list. Queues are used in many algorithms and applications, such as job scheduling, task processing, and network packet handling.
Here is an example of creating a queue using an array in JavaScript:
class Queue {
constructor() {
this.items = [];
}
enqueue(item) {
this.items.push(item);
}
dequeue() {
if (this.isEmpty()) {
return null;
}
return this.items.shift();
}
peek() {
if (this.isEmpty()) {
return null;
}
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
clear() {
this.items = [];
}
}
In this example, the Queue class is defined with several methods, including enqueue(), dequeue(), peek(), isEmpty(), size(), and clear(). The enqueue() method adds a new item to the back of the queue, while the dequeue() method removes and returns the front item from the queue. The peek() method returns the front item from the queue without removing it. The isEmpty() method returns true if the queue is empty, and false otherwise. The size() method returns the number of items in the queue. The clear() method removes all items from the queue.
Here are some examples of how to use the Queue class:
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
console.log(queue.size()); // Output: 3
console.log(queue.peek()); // Output: 1
console.log(queue.dequeue()); // Output: 1
console.log(queue.size()); // Output: 2
console.log(queue.isEmpty()); // Output: false
queue.clear();
console.log(queue.size()); // Output: 0
In this example, we create a new Queue object and add several items to it using the enqueue() method. We then use the size(), peek(), dequeue(), and isEmpty() methods to access and manipulate the items in the queue, and the clear() method to remove all items from the queue.
Queues can be used in a variety of applications, such as message queues, printer queues, and web server request handling.