代码随想录算法训练营第第十天 | 232.用栈实现队列 、225. 用队列实现栈

232.用栈实现队列

题目链接/文章讲解/视频讲解:https://programmercarl.com/0232.用栈实现队列.html


var MyQueue = function() {
    this.stackIn = [];
    this.stackOut = [];
};

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

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    if(this.stackOut.length>0){
        return this.stackOut.pop();
    }
    while(this.stackIn.length>0){
        this.stackOut.push(this.stackIn.pop());
    }
    return this.stackOut.pop();
    
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    let res = this.pop();
    this.stackOut.push(res);
    return res;
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    if (this.stackOut.length ===0 && this.stackIn.length===0) {
        return true;
    }
    return false;
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * var obj = new MyQueue()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.peek()
 * var param_4 = obj.empty()
 */
  1. 用队列实现栈

可以大家惯性思维,以为还要两个队列来模拟栈,其实只用一个队列就可以模拟栈了。
建议大家掌握一个队列的方法,更简单一些,可以先看视频讲解
题目链接/文章讲解/视频讲解:https://programmercarl.com/0225.用队列实现栈.html

用一个队列实现比较简单
var MyStack = function() {
    this.queue1 = [];
    this.queue2 = [];
};

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

/**
 * @return {number}
 */
MyStack.prototype.pop = function() {
    if (this.queue1.length===0) {
        [this.queue1, this.queue2] = [this.queue2, this.queue1];
    }
    while(this.queue1.length>1){
        this.queue2.push(this.queue1.shift());
    }
    return this.queue1.shift();
};

/**
 * @return {number}
 */
MyStack.prototype.top = function() {
    let res = this.pop();
    this.push(res);
    return res;
};

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
    return !(this.queue1.length || this.queue2.length);
};

/**
 * 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()
 */
posted @ 2024-05-18 00:37  YuanYF6  阅读(2)  评论(0编辑  收藏  举报