javascript实现用两个队列实现栈,用一个队列实现栈,用两个栈实现队列

**两个栈实现队列思路:**添加元素的话直接push到栈1,删除队列头部的话是当栈2为空的时候需要先把栈1的元素全放到栈2,然后栈2在pop即可,当栈1栈2的长度都为空时,返回-1,否则栈2有长度直接pop即可。

var MyQueue = function() {
    this.stack1=[];
    this.stack2=[];
};
MyQueue.prototype.push = function(x) {
    this.stack1.push(x)
};
MyQueue.prototype.pop = function() {
    if(this.stack2.length===0){
        while(this.stack1.length){
            this.stack2.push(this.stack1.pop())           
        }
        return this.stack2.pop()
    }
    if(this.stack2.length===0){
        return null;
    }
    return this.stack2.pop();
};
MyQueue.prototype.peek = function() {
    // const x = this.pop();
    // this.stack2.push(x)
    // return x
    if(!this.stack2.length&&!this.stack1.length){
        return null
    }
    if(this.stack2.length){
        return this.stack2[this.stack2.length-1]
    }else{
        return this.stack1[0]
    }
};
MyQueue.prototype.empty = function() {
    return !this.stack1.length&&!this.stack2.length
};

**两个队列实现栈思路:**队列1用于直接push数据,当出栈时,队列1将元素全部出队列放至队列2,直到队列1只剩下一个数据时,那么这个就是需要出栈的值,记录当前出栈的值,又将队列2出列全部放到队列1,后续即可进行同样的操作。

var MyStack = function() {
    this.queue1=[];
    this.queue2=[]
};
MyStack.prototype.push = function(x) {
    this.queue1.push(x);
};
MyStack.prototype.pop = function() {
    while(this.queue1.length > 1){
        this.queue2.push(this.queue1.shift())
    }
    var ans = this.queue1.shift();
    while(this.queue2.length){
        this.queue1.push(this.queue2.shift())
    }
    return ans
};
MyStack.prototype.top = function() {
    return this.queue1.slice(-1)[0]//slice(-1)也可   
};
MyStack.prototype.empty = function() {
    return !this.queue1.length
};

**一个队列实现栈:**将队列以数组的形式,使用push和pop方法即可。

var MyStack = function() {
    this.queue=[]
};
MyStack.prototype.push = function(x) {
    this.queue.push(x);
};
MyStack.prototype.pop = function() {
    return this.queue.pop()
};
MyStack.prototype.top = function() {
    if(this.queue.length===0){
        return null
    }
    return this.queue[this.queue.length-1]
};
MyStack.prototype.empty = function() {
    return this.queue.length===0
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值