In a queue, removing elements is based on the First-In-First-Out (FIFO) principle, so the first element added is also the first to be removed. In computer science, queues are used in a wide variety of applications, including operating systems, network programming, and data processing.
class Queue {
constructor() {
this.items = [];
}
// The functions that need to be implemented
// enqueue(item)
// dequeue()
// peek()
// isEmpty()
}
class Queue {
constructor()
{
this.items = [];
}
}
An element is pushed to the top of the stack with this operation.
enqueue(element) {
this.items.push(element);
}
An element at the top of a stack is removed using this operation.
dequeue() {
this.items.shift();
}
In peek, the top element of a stack is returned without being removed.
peek() {
this.items[0];
}
Checks whether the stack is empty by using IsEmpty.
isEmpty() {
this.items.length == 0;
}
class Queue {
constructor() {
this.items = {};
this.headIndex = 0;
this.tailIndex = 0;
}
enqueue(item) {
this.items[this.tailIndex] = item;
this.tailIndex++;
}
dequeue() {
const item = this.items[this.headIndex];
delete this.items[this.headIndex];
this.headIndex++;
return item;
}
peek() {
return this.items[this.headIndex];
}
get length() {
return this.tailIndex - this.headIndex;
}
}
const queue = new Queue();
queue.enqueue(1);
console.log(queue); // Queue { items: { '0': 1 }, headIndex: 0, tailIndex: 1 }
queue.enqueue(2);
console.log(queue); // Queue { items: { '0': 1, '1': 2 }, headIndex: 0, tailIndex: 2 }
queue.enqueue(3);
console.log(queue); // Queue { items: { '0': 1, '1': 2, '2': 3 }, headIndex: 0, tailIndex: 3 }
console.log(queue.dequeue()); // 1
console.log(queue); // Queue { items: { '1': 2, '2': 3 }, headIndex: 1, tailIndex: 3 }
//length
console.log(queue.length) // 2
//isEmpty
console.log(queue.length == 0) // false
//Peek
console.log(queue.peek()) // 2