A queue is a linear data structure that follows the First In, First Out (FIFO) principle, meaning that the first element added to the queue is the first one to be removed. It can be envisioned as a line of people waiting for a service, where the person who joined the line first is served first.
Operations:
- Enqueue: Adds an element to the rear (end) of the queue.
- Dequeue: Removes and returns the front (first) element of the queue.
- Front/Peek: Returns the front element of the queue without removing it.
- isEmpty: Checks if the queue is empty.
- Size: Returns the number of elements in the queue.
JavaScript Implementation:
class Queue{
constructor(){
this.data = [];
this.front = 0;
this.rear = 0;
}
enqueue(data){
this.data[this.rear] = data;
this.rear++;
}
isEmpty(){
return this.front === this.rear;
}
dequeue(){
if(this.isEmpty()){
return console.log("null");
}
else{
console.log("dequeue value are : " + this.data[this.front]);
this.front++;
return ;
}
}
getFront(){
if(this.isEmpty()){
return console.log("null ");
}
else{
return console.log("getFront : " + this.data[this.front]);
}
}
printQueue() {
if (this.isEmpty()) {
return console.log("Queue is empty");
}
const front = this.front;
// Loop until front reaches rear (all elements printed)
while (this.front !== this.rear) {
console.log("printQueue : " + this.data[this.front]);
this.front++;
}
this.front = front;
}
}
const queue = new Queue();
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.getFront()
queue.dequeue()
queue.getFront()
queue.printQueue()
queue.getFront()
Advantages of Queue:
Order Preservation: Queues preserve the order of elements, ensuring that elements are processed in the order they were added.
Efficiency: Enqueuing and dequeuing operations have a time complexity of O(1), making queues efficient for managing elements in a FIFO manner.
Concurrency Control: Queues are commonly used in multi-threaded applications for managing tasks or messages, ensuring that tasks are processed in a controlled and organized manner.
Disadvantages of Queue:
Limited Access: Similar to stacks, queues provide limited access to elements. You can only access the front element without removing it, and accessing other elements requires dequeuing elements from the queue.
Fixed Size: In some implementations, the size of a queue may be fixed, leading to potential overflow errors if the queue exceeds its capacity.
Not Suitable for All Use Cases: While queues are useful for managing tasks, messages, and data in a FIFO manner, they may not be the best choice for all applications, especially those requiring more complex access patterns.
Conclusion:
https://github.com/ajithr116/Data-Structures/tree/main/09-queue are essential data structures with various applications in computer science, software engineering, and everyday life. Understanding queues and their operations is crucial for designing efficient algorithms and systems that require orderly processing of elements.
Top comments (0)