Queue
Queue is an Abstact data structure, similar to Stacks, but differs, a queue is open at its both ends, One end is used to insert data (enque) and the other is used to removed data (dequeue). Queue follows First-in-First-Out methodology.
A real-world example is a queue of people waiting for getting vaccinated for covid. First comers will get vaccinated first.
Operations
Fundamental Operation ::
1. enqueue() -- store an item to the queue;
2. dequeue() -- remove an item from the head/first element
Auxilary operation::
1. peek() -- Get the first element with-out dequeue()
2. isfull() -- Checks if the queue is full.
3. isempty() -- Checks if the queue is empty.
Javascript implementation of Queue (Linked-List)
// Queue implementation in linked list
// Node class
class Node {
constructor(value){
this.value = value;
this.next = null;
}
}
class Queue {
constructor(){
this.first = null;
this.last = null;
this.length = 0;
}
peek(){
// check if the list if empty
if(this.length === 0 ) return 'List is empty';
return this.first
}
enqueue(value){
const newNode = new Node(value);
// check if the list if empty
if (this.length === 0){
this.first = newNode;
this.last = this.first;
}else {
this.last.next = newNode;
this.last = newNode
}
this.length++
return this
}
dequeue(){
if(!this.first){//if first is equal null
return 'Empty List'
}
if(this.first == this.last){
this.last = null; //remove the last reference
}
const holding = this.first.next;
this.first = holding;
this.length--;
return this;
}
}
// new instance of the Queue
const queue = new Queue()
// peek
console.log(queue.peek())
// enque first node
console.log(queue.enqueue("Gopi"))
console.log(queue.enqueue("Venkata"))
console.log(queue.enqueue("Poorna"))
// peek again
console.log(queue.peek())
// Dequeue
console.log(queue.dequeue())
console.log(queue.dequeue())
console.log(queue.dequeue())
console.log(queue.dequeue())
Top comments (0)