这题听船长和助教将都能听懂,所以上来直接开撸,整体都能撸出来,就是关键的while循环我想着写一个for循环,把pushArr里面的元素转移到popArr中,但是忘记清空pushArr了,还有一个问题就是pop()的时候忘记return了 最后
/**
* Initialize your data structure here.
*/
var MyQueue = function() {
this.arrPush = [];
this.arrPop = [];
};
/**
* Push element x to the back of queue.
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.arrPush.push(x)
};
/**
* Removes the element from in front of queue and returns that element.
* @return {number}
*/
MyQueue.prototype.pop = function() {
if(!this.arrPop.length){
while(this.arrPush.length){
this.arrPop.push(this.arrPush.pop())
}
}
return this.arrPop.pop();
};
/**
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function() {
if(!this.arrPop.length){
// 我这for循环之后清空还是不行 记录一下
// for(const item of this.arrPush) {
// this.arrPop.push(item)
// }
// this.arrPush = []
while(this.arrPush.length){
this.arrPop.push(this.arrPush.pop())
}
}
// 方法一
const num = this.arrPop.pop();
this.arrPop.push(num)
return num;
// 方法二
// return this.arrPop[this.arrPop.length - 1]
};
/**
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return !this.arrPop.length && !this.arrPush.length;
};
/**
* 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()
*/