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=[];// s1中存储的是后入队的元素this.s2=[];// s2中存储的是先入队的元素this.top=null;// 储存队首,如果s2中有元素,则s2的栈顶为队首};/** * 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;}// 后入队的元素都保存在s1this.s1.push(x);};/** * Removes the element from in front of queue and returns that element. * @return {number} */MyQueue.prototype.pop=function(){// s2中保存的是先入队的元素,因此要先出队if(this.s2.length){returnthis.s2.pop();}// 如果s2为空,将s1中元素存入s2,进行出队操作while(this.s1.length){this.s2.push(this.s1.pop());}// 因为将s1元素存入s2,所以队首始终在在s2的栈顶returnthis.s2.pop();};/** * Get the front element. * @return {number} */MyQueue.prototype.peek=function(){// 如果s2中有元素,则栈顶即为队首if(this.s2.length){returnthis.s2[this.s2.length-1];}// s2中无元素,则此时队首在topreturnthis.top;};/** * Returns whether the queue is empty. * @return {boolean} */MyQueue.prototype.empty=function(){// 由于s1的元素只有在pop时才会转移到s2,因此判空时要两个栈一起判断return!this.s1.length&&!this.s2.length;};
The text was updated successfully, but these errors were encountered:
原题链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/
解题思路:
参考了官方题解中的方法二(使用两个栈 入队 - O(1)O(1),出队 - 摊还复杂度 O(1)O(1))。
The text was updated successfully, but these errors were encountered: