Junior — Middle
Can you explain how a queue data structure functions?
sobes.tech AI
Answer from AI
A queue is a data structure that operates on the FIFO (First In, First Out) principle, meaning the first element added is the first to be removed. Elements are added to the end of the queue and removed from the front. This is convenient for organizing sequential processing of tasks or messages.
Example of a queue implementation in JavaScript:
class Queue {
constructor() {
this.items = [];
}
enqueue(element) {
this.items.push(element); // add to the end
}
dequeue() {
if(this.isEmpty()) return null;
return this.items.shift(); // remove from the front
}
isEmpty() {
return this.items.length === 0;
}
peek() {
return this.isEmpty() ? null : this.items[0];
}
}
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
console.log(queue.dequeue()); // 1
console.log(queue.peek()); // 2