Queue is a linear data structure, similar to stack, that works on the First-In-First-Out (FIFO) principle. This is best illustrated through the following real life example. Think of people lining up at the movie theater kiosk to buy tickets. The person at the front of the line will get his or her ticket first and leave, whereas the person at the end of line will get his or her ticket much later. Anyone joining the line afterwards will obviously get their ticket after them.
Quese has two basic operations:
- Enqueue - adding an element at the end of it
- Dequeue - removing an element at the end of it
Look at the code below to see how this concept is exemplified in a queue class using an array.
class Queue {
constructor() {
this.items = [];
}
// Adds an element to the queue
enqueue(element) {
this.items.push(element);
}
//Removes an element from the queue
dequeue() {
this.items.shift();
}
// returns the Front element of the queue without removing it.
front() {
if(this.items.length == 0){
return "No elements in Queue";
}
return this.items[0];
}
}
// creating object for queue class
var queue = new Queue();
// Adding elements to the queue. Queue contains [1, 2, 3, 4, 5]
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue(5);
// returns 1
console.log(queue.front());
// removes 1 from the queue. Queue contains [2, 3, 4, 5]
console.log(queue.dequeue());
// returns 2
console.log(queue.front());
// removes 2. Queue contains [3, 4, 5]
console.log(queue.dequeue());
Top comments (0)