代码随想录day10| 232.用栈实现队列、225. 用队列实现栈

65 阅读1分钟

栈:先进后出 队列:先进先出

不能像数列一样又有pop又有shift,只有pop,出能出的那个,对于队列来说就是先进元素,对于栈来说就是后进元素

对于js来说,既没有栈,也没有队列,都是使用数组模拟。

232.用栈实现队列

思路: pop对应的元素不一样,所以想用栈实现队列需要两个栈,pop的时候倒一下

最开始的想法是stack1放入stack2,pop完再倒回去,但其实并没有必要倒回去, pop函数只有在stack2没值的时候才需要进行stack1倒入stack2的操作,否则一直从stack2走,这样两个栈不会乱。

image.png

// 使用两个数组的栈方法(push, pop) 实现队列
/**
* Initialize your data structure here.
*/
var MyQueue = function() {
   this.stack1 = [];
   this.stack2 = [];
};

/**
* Push element x to the back of queue. 
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
   this.stack1.push(x);
};

/**
* Removes the element from in front of queue and returns that element.
* @return {number}
*/
MyQueue.prototype.pop = function() {
   const size = this.stack2.length;
   if(size) {
       return this.stack2.pop();
   }
   while(this.stack1.length) {
       this.stack2.push(this.stack1.pop());
   }
   return this.stack2.pop();
};

/**
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function() {
   const x = this.pop();
   this.stack2.push(x);
   return x;
};

/**
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
   return !this.stack1.length && !this.stack2.length
};

225. 用队列实现栈

用队列实现栈只需要一个队列就可以了,因为出队列再入队列,不会改变原来的顺序 用数组的pushshift模拟队列,再用这个队列实现栈


var MyStack = function () {
    this.queue = []
};

/** 
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function (x) {
    this.queue.push(x)
};

/**
 * @return {number}
 */
MyStack.prototype.pop = function () {
    const size = this.queue.length
    let cur = 0
    let res = null
    while (cur < size) {
        if (cur === size - 1) {
            res = this.queue.shift()
        } else {
            this.queue.push(this.queue.shift())
        }
        cur++
    }
    return res

};

/**
 * @return {number}
 */
MyStack.prototype.top = function () {
    const x = this.pop()
    this.queue.push(x)
    return x

};

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function () {
    console.log(this.queue)
    return this.queue.length === 0
};

/**
 * Your MyStack object will be instantiated and called as such:
 * var obj = new MyStack()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.empty()
 */

pop函数优化:


MyStack.prototype.pop = function() {
    let size = this.queue.length;
    while(size-- > 1) {
        this.queue.push(this.queue.shift());
    }
    return this.queue.shift();
};