力扣刷题day4(用两个队列实现栈)

文章目录

题目

在这里插入图片描述

思路

:先进后出对应数组的push()和pop()
队列:先进先出对应数组的push()和shift()

  1. 首先就是分为两个栈,一个是入队栈另一个是出队栈; 入队栈就专门用来存入数据,出队栈就是用来操作出队。
  2. 对于入队,就直接调用push()函数即可;
  3. 对于出队,首先要检查出队栈是否有数据,如果有的数据就调用pop()删除,如果没有的话,就需要从入队栈将数据进行存入,然后再删除。

代码

var CQueue = function()
{
    
    
    this.stackA=[];
    this.stackB=[];
}
CQueue.prototype.appendTail=function(value)
{
    
    
    this.stackA.push(value)
}
CQueue.prototype.deleteHead=function()
{
    
    
    if(this.stackB.length)
    {
    
    
        return this.stackB.pop()
    }else{
    
    
        while(this.stackA.length)
        {
    
    
            this.stackB.push(this.stackA.pop())
        }
        if(!this.stackB.length)
        {
    
    
            return -1
        }else{
    
    
            return this.stackB.pop()
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_51610980/article/details/128377213