232. 用栈实现队列

一开始觉得挺脑瘫一题,后来发现自己对栈的理解还不够透彻。

一开始的想法是,对于比较复杂的pop和peek操作,每次都都从mainStack转移到tempStack,形成一次逆序,然后再从tempStack取栈顶,结束后再移回mainStack。其实一开始就觉得这个方法是最垃圾的办法,但是也是最稳妥的办法,所以就没继续多想,往下写了。

后来看了题解以后,发现这个tempStack的用法还可以用的更高级一些。

对于mainStack,所有的push操作,都在里面进行。如果出现pop或peek操作,就把main中的元素逆序填入temp,这样temp中的元素始终是优先级最高的一批队列序的元素。只要temp不为空,就优先从temp中pop或peek元素,直到temp为空后,再从main中逆序填入temp。

/**
 * Initialize your data structure here.
 */
var MyQueue = function() {
    this.mainStack = [];
    this.tempStack = [];
};

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

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

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    if (this.tempStack.length === 0) {
        while(this.mainStack.length !== 0) {
            this.tempStack.push(this.mainStack.pop());
        };
    }
    return this.tempStack[this.tempStack.length - 1];
};

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

/**
 * 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()
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值