A queue is a data structure that stores items according to the First In First Out (FIFO) principle. The item that has been in the queue the longest is the first one to be removed.
In a queue, operations occur at both ends, so using an array is not efficient since removing the first element is costly. A linked list implementation is more suitable.
Queue
class QueueNode { constructor(value) { this.value = value; this.next = null; }}class Queue { constructor() { this.head = null; this.tail = null; this.size = 0; } enqueue(value) { const newNode = new QueueNode(value); if (this.head === null) { this.head = newNode; } else { this.tail.next = newNode; } this.tail = newNode; this.size++; } dequeue() { if (this.head === null) { throw new Error('queue is empty'); } const value = this.head.value; this.head = this.head.next; this.size--; if (this.head === null) { this.tail = null; } return value; } peek() { if (this.head === null) { throw new Error('queue is empty'); } return this.head.value; }}
Usage:
const myQueue = new Queue();myQueue.enqueue('One');myQueue.enqueue('Two');myQueue.enqueue('Three');console.log(myQueue.peek()); // Oneconsole.log(myQueue.dequeue()); // Oneconsole.log(myQueue.dequeue()); // Twoconsole.log(myQueue.dequeue()); // Threeconsole.log(myQueue.peek()); // Error: queue is empty