原题链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/
解题思路:
参考了官方题解中的方法一(使用两个栈 入队 - O(n)O(n), 出队 - O(1)O(1))。
- 入队时,将s1的元素倒过来存入s2。
- 再将入队元素存在s2的栈顶,这样s2中的元素顺序就与入队顺序相同。
- 最后将s2元素再倒过来存入s1,这样s1中元素的顺序与入队顺序相反,此时进行出栈操作的元素就与出队操作相同。
/**
* Initialize your data structure here.
*/
var MyQueue = 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中元素缓存到s2
while (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 () {
return this.s1.pop();
};
/**
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function () {
return this.s1[this.s1.length - 1];
};
/**
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function () {
return !this.s1.length;
};