Likou brush question day4 (using two queues to implement the stack)

Article directory

topic

insert image description here

train of thought

Stack : FIFO corresponds to push() and pop() of the array
Queue : FIFO corresponds to push() and shift() of the array

  1. First of all, it is divided into two stacks, one is the queue stack and the other is the queue stack; the queue stack is specially used to store data, and the queue stack is used to operate the queue.
  2. For entering the queue, just call the push() function directly;
  3. For dequeuing, first check whether there is data in the dequeue stack. If there is data, call pop() to delete it. If not, you need to store the data from the queue stack, and then delete it.

the code

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()
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_51610980/article/details/128377213