思路
这道题目是让我们用栈来模拟实现队列。 我们知道栈和队列都是一种受限的数据结构。 栈的特点是只能在一端进行所有操作,队列的特点是只能在一端入队,另一端出队。
在这里我们可以借助另外一个栈,也就是说用两个栈来实现队列的效果。这种做法的时间复杂度和空间复杂度都是O(n)。
由于栈只能操作一端,因此我们peek或者pop的时候也只去操作顶部元素,要达到目的 我们需要在push的时候将队头的元素放到栈顶即可。
因此我们只需要在push的时候,用一下辅助栈即可。 具体做法是先将栈清空并依次放到另一个辅助栈中,辅助栈中的元素再次放回栈中,最后将新的元素push进去即可
/*** Initialize your data structure here.*/var MyQueue = function() {this.stack = []this.helperStack = []};/*** Push element x to the back of queue.* @param {number} x* @return {void}*/MyQueue.prototype.push = function(x) {this.stack.push(x)};/*** Removes the element from in front of queue and returns that element.* @return {number}*/MyQueue.prototype.pop = function() {while(this.stack.length) {this.helperStack.push(this.stack.pop())}let item = this.helperStack.pop()while(this.helperStack.length) {this.stack.push(this.helperStack.pop())}return item};/*** Get the front element.* @return {number}*/MyQueue.prototype.peek = function() {return this.stack[0]};/*** Returns whether the queue is empty.* @return {boolean}*/MyQueue.prototype.empty = function() {if(this.stack.length) return falsereturn true};/*** 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()*/
