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=[];// 入队时缓存s1};/** * Push element x to the back of queue. * @param {number} x * @return {void} */MyQueue.prototype.push=function(x){// 将s1中元素缓存到s2while(this.s1.length){this.s2.push(this.s1.pop());}// 入队元素缓存到s2的栈顶,this.s2.push(x);// 将s2元素存回s1,新入队的元素变为栈底,栈顶则是队首元素while(this.s2.length){this.s1.push(this.s2.pop());}};/** * Removes the element from in front of queue and returns that element. * @return {number} */MyQueue.prototype.pop=function(){returnthis.s1.pop();};/** * Get the front element. * @return {number} */MyQueue.prototype.peek=function(){returnthis.s1[this.s1.length-1];};/** * 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/
解题思路:
参考了官方题解中的方法一(使用两个栈 入队 - O(n)O(n), 出队 - O(1)O(1))。
The text was updated successfully, but these errors were encountered: