creating a new Queue - Node.js Data Structure

Node.js examples for Data Structure:Queue

Description

creating a new Queue

Demo Code


class Queue {//from w  w  w .  j  a  v a 2  s  .co  m
    constructor () {
        this.head = 0;
        this.data = [];
    }
}

let q = new Queue;
Queue.prototype.enqueue = function (value) {
    this.data.push(value)
    
}

Queue.prototype.dequeue = function () {
    if(this.head < 0 || this.head > this.data.length){
        return null;
    }
    //first call do deque will be at this.data[0]
    var dequedItem = this.data[this.head];
    //the 'this.data' array remains the same
    //we increment this.head so that the next call will point to the next item in the array
    this.head++
    
    return dequedItem;
    
}

q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
console.log(q.dequeue())
console.log(q.dequeue())
console.log(q)

Related Tutorials