每次 pop 或peek时,若输出栈为空则将输入栈的全部数据依次弹出并压入输出栈,这样输出栈从栈顶往栈底的顺序就是队列从队首往队尾的顺序。
二、代码实现
// 面对对象编程varMyQueue=function(){// 定义两个栈,用数组实现栈的操作this.inputStack =[],this.outputStack =[];};// 入队,即将数据压入输入栈中MyQueue.prototype.push=function(x){this.inputStack.push(x);};// 从队头移除并返回元素,即当输出栈为空的时候,将输入栈的元素弹出并且压入输出栈中// 这里需要用if,因为只需要得到一个元素MyQueue.prototype.pop=function(){if(!this.outputStack.length){this.out_to_in();}returnthis.outputStack.pop();};// 返回队头的元素,即和pop()的作用一致,只是不删除元素MyQueue.prototype.peek=function(){if(!this.outputStack.length){this.out_to_in();}returnthis.outputStack[this.outputStack.length-1];};// 当输入栈不空的时候,将输入栈的元素弹出,压到输出栈中// 注意这里要用while,因为可能之前在输入栈中压入了多个元素,如果只操作一个元素,得到的并不是队头的元素MyQueue.prototype.out_to_in=function(){while(this.inputStack.length){let x =this.inputStack.pop();this.outputStack.push(x);}}// 检查队列是否为空,即检查输入栈和输出栈是否均为空MyQueue.prototype.empty=function(){if(this.inputStack.length ==0&&this.outputStack.length ==0)returntrue;returnfalse;};/**
* Your MyQueue object will be instantiated and called as such:
* var obj = new MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/