Appearance
232. 用栈实现队列
- 一个入队栈,一个出队栈
- 入队的时候正常
- 出队的时候判断如果有元素就出,没有元素将入队栈的元素逆序导出到出队栈
js
var MyQueue = function() {
// 入队栈
this.pushStack = []
// 出队栈
this.popStack = []
// 队列长度
this.size = 0
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
// 入队栈添加元素
this.pushStack.push(x)
this.size++
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function() {
// 判空
if(this.empty()) return null
// 判断出队栈是否有元素,没有元素要从入队栈中倒过去
this.peek()
this.size--
// 返回删除的元素
return this.popStack.pop()
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
if(this.empty()) return null
// 如果出队栈为空,就从入队栈中导入元素
if (this.popStack.length === 0) {
while(this.pushStack.length > 0) {
this.popStack.push(this.pushStack.pop())
}
}
// 返回最后一个元素
return this.popStack[this.popStack.length - 1]
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return this.size === 0
};
/**
* 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()
*/