Article directory
topic
train of thought
Stack : FIFO corresponds to push() and pop() of the array
Queue : FIFO corresponds to push() and shift() of the array
- 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.
- For entering the queue, just call the push() function directly;
- 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()
}
}
}