Quick actions

cmd+k|ctrl+k

Navigation

Languages

Queue with Stacks

Snippet info

Language

JavaScript

Visibility

public

Author

varun.muriyanat

Created

2025-05-02T14:39:24.29568Z

Updated

2025-05-02T19:28:57.013247Z

class Node {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

class Queue {
    constructor() {
        this.arr = [];
    }
    
    peek() {
        if (this.arr.length !== 0) {
            return this.arr[0];    
        }
        return null;
    }
    
    push(value) {
        this.arr.push(value);
        return this;
    }
    
    pop() {
        if (this.arr.length === 0) {
            return null;
        }
        
        return this.arr.shift();
    }
    
    isEmpty() {
        return (this.length === 0);
        
    }
    
    // print the elements in the queue
    printList() {
        console.log(this.arr.join(" | "));
    }
}

const myQueue = new Queue();
// console.log(myQueue.isEmpty());
myQueue.push(10);
myQueue.push(20);
myQueue.push(30);
myQueue.push(40);
myQueue.printList();
// console.log(myQueue.peek());
// myQueue.printList();
console.log(myQueue.pop());
myQueue.printList();
console.log(myQueue.pop());
myQueue.printList();
console.log(myQueue.pop());
myQueue.printList();
console.log(myQueue.pop());
myQueue.printList();
console.log(myQueue.pop());
myQueue.printList();
INFO