Quick actions

cmd+k|ctrl+k

Navigation

Languages

Implementation of Queue Using Stacks

Snippet info

Language

JavaScript

Visibility

public

Author

dhamankovachi1

Created

2023-11-09T11:06:05.48139Z

Updated

2023-11-10T12:49:57.505466Z

class Queue{
    constructor(){
        this.first=[];
        this.last=[];
    }
    
    enqueue(value){   
        const length=this.first.length
        for(let i=0;i<length;i++){    // Here it will put all the values of first stack in second stack upside down if there are any
            this.last.push(this.first.pop());
        }
        this.last.push(value);                  //Here it will push the value at the top of second stack 
        return this;
    }
    
    dequeue(){
        const length=this.last.length
        for (let i = 0; i < length; i++) {
            this.first.push(this.last.pop());
        }
        this.first.pop();
        return this;
    }
    
    peek(){
        if(this.last.length>0){
            return this.last[0];
        }
        return this.first[this.first.length-1];
    }
    
}

const q=new Queue();
q.peek();
q.enqueue(68);
q.enqueue(57);
q.dequeue();
INFO