#232. Implement Queue using Stacks

ยท

1 min read

https://leetcode.com/problems/implement-queue-using-stacks/?envType=daily-question&envId=2024-01-29


var MyQueue = function () {
    this.stack = []
    this.stack2 = []
};

/** 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function (x) {
    while (this.stack.length > 0) {
        this.stack2.push(this.stack.pop())
    }

    this.stack.push(x)

    while (this.stack2.length > 0) {
        this.stack.push(this.stack2.pop())
    }

};

/**
 * @return {number}
 */
MyQueue.prototype.pop = function () {
   return this.stack.pop()
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function () {
    return this.stack[this.stack.length - 1]
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function () {
    return this.stack.length === 0
};

One thing to note whenever questions like stack using queues or queue using stacks comes up is that it going to use either two queues or two stacks to build the other and there would be pouring of the stack's item to the second stack before insertion, after this, you can carry out the normal array functions without any problem.

ย