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=[];// 用于存储入栈元素,且保证栈的顺序};/** * Push element x onto stack. * @param {number} x * @return {void} */MyStack.prototype.push=function(x){// 每个入栈元素存储在q2,以保证其是第一个元素,也就是会第一个popthis.q2.push(x);// 把q1的元素依次移入q2,实现了出栈顺序while(this.q1.length){this.q2.push(this.q1.shift());}// 将q1和q2对调,保证每次出入栈操作的对列一致consttemp=this.q1;this.q1=this.q2;this.q2=temp;};/** * Removes the element on top of the stack and returns that element. * @return {number} */MyStack.prototype.pop=function(){returnthis.q1.shift();};/** * Get the top element. * @return {number} */MyStack.prototype.top=function(){returnthis.q1[0];};/** * 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(n)O(n), 弹出 - O(1)O(1))。
在入栈时将队列的元素按照出栈的顺序排列好,在出栈时就可以按顺序出栈。
The text was updated successfully, but these errors were encountered: