一开始觉得挺脑瘫一题,后来发现自己对栈的理解还不够透彻。
一开始的想法是,对于比较复杂的pop和peek操作,每次都都从mainStack转移到tempStack,形成一次逆序,然后再从tempStack取栈顶,结束后再移回mainStack。其实一开始就觉得这个方法是最垃圾的办法,但是也是最稳妥的办法,所以就没继续多想,往下写了。
后来看了题解以后,发现这个tempStack的用法还可以用的更高级一些。
对于mainStack,所有的push操作,都在里面进行。如果出现pop或peek操作,就把main中的元素逆序填入temp,这样temp中的元素始终是优先级最高的一批队列序的元素。只要temp不为空,就优先从temp中pop或peek元素,直到temp为空后,再从main中逆序填入temp。
/**
* Initialize your data structure here.
*/
var MyQueue = function() {
this.mainStack = [];
this.tempStack = [];
};
/**
* Push element x to the back of queue.
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.mainStack.push(x);
};
/**
* Removes the element from in front of queue and returns that element.
* @return {number}
*/
MyQueue.prototype.pop = function() {
if (this.tempStack.length === 0) {
while(this.mainStack.length !== 0) {
this.tempStack.push(this.mainStack.pop());
}
}
return this.tempStack.pop();
};
/**
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function() {
if (this.tempStack.length === 0) {
while(this.mainStack.length !== 0) {
this.tempStack.push(this.mainStack.pop());
};
}
return this.tempStack[this.tempStack.length - 1];
};
/**
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return this.mainStack.length === 0 && this.tempStack.length === 0;
};
/**
* 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()
*/