You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/** * Initialize your data structure here. */varMyQueue=function(){this.s1=[];// 储存队列this.s2=[];// pop时临时存储数据this.top=null;// 储存队首};/** * Push element x to the back of queue. * @param {number} x * @return {void} */MyQueue.prototype.push=function(x){// 将第一个入队元素存储为队首if(!this.s1.length){this.top=x;}// 所有元素正常入栈this.s1.push(x);};/** * Removes the element from in front of queue and returns that element. * @return {number} */MyQueue.prototype.pop=function(){// s1长度为1时,栈会被清空,因此清空队首的值,但此处用例没有校验if(this.s1.length<=1){this.top=null;}// 将s1元素除队首全部都转移到s2while(this.s1.length>1){this.top=this.s1.pop();this.s2.push(this.top);}// 将队首元素出栈并缓存constpop=this.s1.pop();// 让s2元素全部返回s1,保持元素的排列顺序while(this.s2.length){this.s1.push(this.s2.pop());}returnpop;};/** * Get the front element. * @return {number} */MyQueue.prototype.peek=function(){returnthis.top;};/** * Returns whether the queue is empty. * @return {boolean} */MyQueue.prototype.empty=function(){return!this.s1.length;};
The text was updated successfully, but these errors were encountered:
原题链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/
解题思路:
The text was updated successfully, but these errors were encountered: