Quick actions

cmd+k|ctrl+k

Navigation

Languages

Queues using 2 Stacks

Snippet info

Language

JavaScript

Visibility

public

Author

anikeshdey2020

Created

2023-02-28T13:53:19.137387Z

Updated

2023-02-28T13:53:19.137387Z

//Implement a Queue which will have array stacks but the push pop order should be First in First Out Like a Queue

class Queue {
    constructor(){
        this.first = []
        this.last = []
        this.length = 0
    }
    
    peek(){
        if(this.length == 0){
            return null;
        }
        
        return this.first[0];
    }
    
    push(value){
        this.first.push(value);
        this.length++;
        return this;
    }
    
    pop(){
        console.log("myQueue.first.length:", this.first.length);
        const firstLength = this.first.length;
        for (let i = 0; i < firstLength; i++){   
            this.last.push(this.first.pop());
        }
        console.log("this.last:", this.last);
        this.last.pop()
        const lastLength = this.last.length;
        for(let j = 0; j < lastLength; j++){
            this.first.push(this.last.pop());
        }

        this.length--;

        return this;
    }
}


const myQueue = new Queue();

myQueue.push(1);

myQueue.push(2);

myQueue.push(3);



myQueue.pop();
INFO