/**
* Initialize your data structure here.
*/varMyQueue=function(){this.inStack =[];this.outStack =[];};/**
* Push element x to the back of queue.
* @param {number} x
* @return {void}
*/MyQueue.prototype.push=function(x){this.inStack.push(x);};/**
* Removes the element from in front of queue and returns that element.
* @return {number}
*/MyQueue.prototype.pop=function(){if(this.empty())return-1;this.moveStack(this.inStack,this.outStack);const x =this.outStack.pop();this.moveStack(this.outStack,this.inStack);return x;};/**
* Get the front element.
* @return {number}
*/MyQueue.prototype.peek=function(){if(this.empty())return-1;this.moveStack(this.inStack,this.outStack);const x =this.outStack[this.outStack.length -1];this.moveStack(this.outStack,this.inStack);return x;};/**
* Returns whether the queue is empty.
* @return {boolean}
*/MyQueue.prototype.empty=function(){returnthis.inStack.length ===0;};MyQueue.prototype.moveStack=function(src, des){while(src.length){
des.push(src.pop());}};
解题二
/**
* Initialize your data structure here.
*/varMyQueue=function(){this.stackNewest =[];this.stackOldest =[];};/**
* Push element x to the back of queue.
* @param {number} x
* @return {void}
*/MyQueue.prototype.push=function(x){this.stackNewest.push(x);// 对 stackNewest 压栈,其顶部元素总是最新的};/**
* Removes the element from in front of queue and returns that element.
* @return {number}
*/MyQueue.prototype.pop=function(){if(this.empty())return-1;this.shiftStacks();// 确保 stackOldest 有当前元素returnthis.stackOldest.pop();// 对最久元素出栈};/**
* Get the front element.
* @return {number}
*/MyQueue.prototype.peek=function(){if(this.empty())return-1;this.shiftStacks();// 确保 stackOldest 有当前元素returnthis.stackOldest[this.stackOldest.length -1];// 获取最久的元素};/**
* Returns whether the queue is empty.
* @return {boolean}
*/MyQueue.prototype.empty=function(){return(this.stackOldest.length +this.stackNewest.length)===0;};MyQueue.prototype.shiftStacks=function(){// 将 stackNewest 的元素移动到 stackOldest// 一般此操作可以让我们对 stackOldest 进行后续操作if(this.stackNewest.length &&!this.stackOldest.length){while(this.stackNewest.length){this.stackOldest.push(this.stackNewest.pop());}}};