化栈为队
要求
实现一个MyQueue类,该类用两个栈来实现一个队列。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size 和 is empty 操作是合法的。 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/im… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
注意
使用JS实现效果,要符合栈的特性,先进后出,后进先出
代码
var MyQueue = function () {
// 定义两个数组,吞进来数组和吐出去数组
this.pushStack = [];
this.popStack = [];
};
/**
* Push element x to the back of queue.
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function (x) {
// 吞进来数组push数据
this.pushStack.push(x);
};
/**
* Removes the element from in front of queue and returns that element.
* @return {number}
*/
MyQueue.prototype.pop = function () {
// 判断吐出去数组有没有值,没值就在吞进来数组里拿
if (!this.popStack.length) {
while (this.pushStack.length) {
this.popStack.push(this.pushStack.pop())
}
}
// 有值了,就吐出去
return this.popStack.pop();
};
/**
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function () {
// 判断吐出去数组有没有值,没值就在吞进来数组里拿
if (!this.popStack.length) {
while (this.pushStack.length) {
this.popStack.push(this.pushStack.pop())
}
}
// 有值了,就赋值一下,然后return
let num = this.popStack[this.popStack.length - 1]
return num;
};
/**
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function () {
// 判断是否有长度,没长度就返回true,有就返回false
return !this.pushStack.length && !this.popStack.length
};