Queue is a linear list of elements in which deletion of an element can take place at one end, called Front
and insertion can take place at the other end, called Rear
The first element in the queue will be the first one to be removed from the list. Queues are also called FIFO(FIRST IN FIRST OUT).
Think of a queue just like a line. It is horizontal. The first one in the line/queue is the first one out. The line starts on the left and ends on the right. Hence you would use pop(), to remove the "last" element of the array.
Applications of the Queue
- Serving request on a single shared resource, eg - PointerEvent, CPU task scheduling, etc,
- In real life, call center phone system(people should wait in and hold until the service representative is free)
- Handling of interrupts in real-time systems.
Basic Operations
The basic operation that can performed are Enqueue
, dequeue
and display
.
Enqueue(terminology for Insertion) - add an item to the queue.
dequeue(terminology for Deletion) - remove an item from the queue
IsEmpty - Checks if the queue is empty.
IsFull - Checks if the queue is full.
Peek - Gets the element at the front of the queue without removing it.
How to use a Queues
Create a queue data structure. The queue should be a class with methods enqueue
and dequeue
.Adding to the queue should store an element until
it is removed.
Functions to be implemented
enqueue(item)
dequeue()
front()
isEmpty()
Examples Usage
const q = new Queue();
q.enqueue(1);
q.dequeue(); // returns 1;
// Queue class
class Queue {
constructor() {
// Array is used to implement a Queue
this.data = [];
}
// Functions to be implemented
// enqueue(item)
// dequeue()
// front()
// isEmpty()
// Adds an element to the queue
enqueue(item) {
this.data.unshift(item);
}
// removing element from the queue
// returns underflow when called
// on empty queue
dequeue() {
if (this.isEmpty()) {
return "Underflow";
}
return this.data.shift();
}
// front function
front() {
// returns the Front element of
// the queue without removing it.
if (this.isEmpty())
return "No elements in Queue";
return this.data[0];
}
// isEmpty function
isEmpty() {
// return true if the queue is empty.
return this.data.length === 0;
}
}
module.exports = Queue;
If you found this article helpful, please click the Follow this channel for more articles on Data Structures using Javascript.
Top comments (6)
You've essentially wrapped another object that already provides the queue-like functionality instead of implementing it yourself
If you really need a double-ended high-performance queue, I have seen it implemented here, with no dependencies.
github.com/lleo/node-dequeue/blob/...
Uses are for
shift
/unshift
often.For Python, it's
from collections import deque
, I think.I think to work with Stacks, Queue is good to work with Node and not with arrays, for performance issues.
Some comments may only be visible to logged-in visitors. Sign in to view all comments.