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. */varMyStack=function(){this.q1=[];// 保存栈this.q2=[];// 用于pop时缓存队列中除栈顶外的其他元素this.tail=null;// 保存栈顶元素};/** * Push element x onto stack. * @param {number} x * @return {void} */MyStack.prototype.push=function(x){this.q1.push(x);// 入栈时将元素直接存入队列this.tail=x;// 由于存入队列的元素无法被作为栈顶查看,因此需要用变量存储此时的栈顶元素};/** * Removes the element on top of the stack and returns that element. * @return {number} */MyStack.prototype.pop=function(){// 如果队列长度<=1,则出栈之后栈顶为空if(this.q1.length<=1){this.tail=null;}// 将队列元素除队尾外都移动到q2,q1中剩下的1个元素即为栈顶元素while(this.q1.length>1){this.tail=this.q1.shift();this.q2.push(this.tail);}// 队列中只剩1个元素,即为栈顶consttop=this.q1.shift();// 将q1和q2对调,保证每次操作的队列都为q1。consttemp=this.q1;this.q1=this.q2;this.q2=temp;// 返回出栈的元素returntop;};/** * Get the top element. * @return {number} */MyStack.prototype.top=function(){returnthis.tail;};/** * Returns whether the stack is empty. * @return {boolean} */MyStack.prototype.empty=function(){return!this.q1.length;};
The text was updated successfully, but these errors were encountered:
原题链接:https://leetcode-cn.com/problems/implement-stack-using-queues/
解题思路:
参考了官方题解的方法一 (两个队列,压入 -O(1)O(1), 弹出 -O(n)O(n))。
入栈时直接将元素存入队列q1,出栈时将q1的非队尾元素存入队列q2,q1中剩下的元素即为栈顶。
The text was updated successfully, but these errors were encountered: