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

232.用栈实现队列

代码

var MyQueue = function() {
    this.stackIn = [];
    this.stackOut = [];
};
​
 // 队列末尾增加元素
MyQueue.prototype.push = function(x) {
    // 数组的方法
    this.stackIn.push(x);
};
​
 // 移除头部并返回
MyQueue.prototype.pop = function() {
    const size = this.stackOut.length;
    if(size){
        // 数组的pop 剪切最后一个元素。最晚入栈的
        return this.stackOut.pop();
    }
    while(this.stackIn.length){
        // 将stackIn的最后一个依次放到stackOut里面
        this.stackOut.push(this.stackIn.pop());
    }
    // 移除stackOut的最后一个,也就是stackIn的第一个 先进先出
    return this.stackOut.pop();
};
​
 // 返回开头元素
MyQueue.prototype.peek = function() {
    // x是最前面的元素
    const x = this.pop();
    this.stackOut.push(x);
    return x;
};
​
 // 是否为空
MyQueue.prototype.empty = function() {
    return ! this.stackIn.length && !this.stackOut.length;
};

225. 用队列实现栈

代码

var MyStack = function() {
    this.queue1 = [];
    this.queue2 = [];
};
​
MyStack.prototype.push = function(x) {
    this.queue1.push(x);
};
​
MyStack.prototype.pop = function() {
    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() {
    const x = this.pop();
    this.queue1.push(x);
    return x;
};
​
MyStack.prototype.empty = function() {
    return !this.queue1.length && !this.queue2.length;
};
var MyStack = function() {
    this.queue = [];
};
​
 // 放入栈顶,先进后出
MyStack.prototype.push = function(x) {
    this.queue.push(x);
};
​
 // 弹出最后放进去的元素
MyStack.prototype.pop = function() {
    let size = this.queue.length;
    while(size-->1){
        this.queue.push(this.queue.shift());
    }
    return this.queue.shift();
};
​
MyStack.prototype.top = function() {
    const x = this.pop();
    this.queue.push(x);
    return x;
};
​
MyStack.prototype.empty = function() {
    return !this.queue.length;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值