225. 用队列实现栈 JavaScript实现

225. 用队列实现栈

题目链接

var MyStack = function() {
    // 一个为主队列,一个为备份队列
    // 主队列的用于输入和输出,备份队列仅用于备份
    this.queue1 = []
    this.queue2 = []
};

MyStack.prototype.push = function(x) {
    // 直接压入主队列
    this.queue1.push(x)
};


MyStack.prototype.pop = function() {
    // 如果需要再次pop元素,此时主队列中元素为空,所以需要将备份队列中的元素移到主队列中
    if(!this.queue1.length){
        [this.queue1,this.queue2] = [this.queue2,this.queue1]
    }

    // 把主队列的元素转移到备份队列,只留下一个元素
    while(this.queue1.length > 1){
        // 从队头弹出,队尾插入
        this.queue2.push(this.queue1.shift())
    }
    // 主队列中的最后一个元素就是需要弹出的元素 
    return this.queue1.shift()
};


MyStack.prototype.top = function() {
    // 思想和pop类似,只是不需要删除元素
    let x = this.pop()
    // 把删除的元素再次压入栈顶元素,补上
    this.queue2.push(x)
    return x
};


MyStack.prototype.empty = function() {
    if(!this.queue1.length && !this.queue2.length){
        return true
    }else{
        return false
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值