这是我参与2022首次更文挑战的第26天,活动详情查看:2022首次更文挑战
实现一个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 操作)。
提示一
队列和栈的主要区别是元素的顺序。队列删除最旧的项,栈删除最新的项。如果你只访问最新的项,那么如何从栈中删除最旧的项?
提示二
我们可以通过不断地删除最新的项(将这些项插入临时栈中)来删除栈中最老的项,直到得到一个元素为止。然后,在检索到最新项后,将所有元素返回。与此有关的问题是,每次在一行中做几个弹出操作(pop)将需要O(n)的时间。我们可以优化在一行中连续弹出这一场景吗?
这个题最核心的就是pop了,用栈来模拟队列的先进先出。当我们需要出的栈 popStack里面没有数据的时候,我们就需要从入栈 pushStack的数据里面拿数据,循环 pushStack,通过 pop 方法把他放在 popStack 中 然后在 pop
/**
* Initialize your data structure here.
*/
var MyQueue = function() {
this.pushStasck = []
this.popStack = []
};
/**
* Push element x to the back of queue.
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.pushStasck.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.pushStasck.length){
this.popStack.push(this.pushStasck.pop())
}
}
return this.popStack.pop()
};
/**
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function() {
if(!this.popStack.length){
while(this.pushStasck.length){
this.popStack.push(this.pushStasck.pop())
}
}
const num = this.popStack.pop()
this.popStack.push(num)
return num
};
/**
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return !this.pushStasck.length && !this.popStack.length
};
/**
* Your MyQueue object will be instantiated and called as such:
* var obj = new MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/