The task is to implement a Queue by using Stack.
The boilerplate code
class Queue {
enqueue(element) {
// add new element to the rare
}
peek() {
// get the head element
}
size() {
// return count of element
}
dequeue() {
// remove the head element
}
}
A Queue follows the First In, First Out rule.
Create an array that stores all the queue elements, and a pointer that points to the front of the queue.
this.items = [];
this.head = 0;
To add an element to the end of the queue
enqueue(element) {
this.items.push(element);
}
To get the front element
peek() {
return this.size() === 0 ? undefined : this.items[this.head];
}
To know how many valid elements are in the queue
size() {
return this.items.length - this.head;
}
To remove the front element
dequeue() {
if (this.size() === 0) return undefined;
const value = this.items[this.head];
this.head++;
return value;
}
Dequeue stores the front value, moves the pointer forward and returns the removed value. If the queue is empty, undefined is returned.
The final code
class Queue {
constructor() {
this.items = [];
this.head = 0;
}
enqueue(element) {
// add new element to the rare
this.items.push(element);
}
peek() {
// get the head element
return this.size() === 0 ? undefined : this.items[this.head];
}
size() {
// return count of element
return this.items.length - this.head;
}
dequeue() {
// remove the head element
if(this.size() === 0) return undefined;
const value = this.items[this.head];
this.head++
if(this.head > 50 && this.head * 2 >= this.items.length) {
this.items = this.items.slice(this.head);
this.head = 0;
}
return value;
}
}
That's all folks!
Top comments (0)