栈
解题思路
用 enStack、outStack 两个栈实现队列,队列是先进先出,栈是后进先出;
push 方法将数据放到 enStack 中,enStack 用来存储数据;
pop 方法:
- 先将 enStack 中的数据依次 pop 出来,放入 outStack 中,此时 outStack 的出栈顺序和队列的出队顺序一致;
- 然后将 outStack 栈顶元素 pop 出去,模拟出队;
- 最后将 outStack 中的数据依次 pop 出来,放入 enStack 中;
图解
复杂度
-
时间复杂度:
O(n)
; -
空间复杂度:
O(n)
;
代码实现
var MyQueue = function () {
this.enStack = [];
this.outStack = [];
};
MyQueue.prototype.push = function (x) {
this.enStack.push(x);
};
MyQueue.prototype.pop = function () {
// 1. 将 enStack 中的数据依次 pop 出来,放入 outStack 中
while (this.enStack.length) this.outStack.push(this.enStack.pop());
// 2. 将 outStack 栈顶元素 pop 出去
const top = this.outStack.pop();
// 3. 将 outStack 中的数据依次 pop 出来,放入 enStack 中
while (this.outStack.length) this.enStack.push(this.outStack.pop());
return top;
};
MyQueue.prototype.peek = function () {
return this.enStack[0];
};
MyQueue.prototype.empty = function () {
return this.enStack.length === 0;
};
leetcode🧑💻 225. 用队列实现栈
上一篇