Appearance
225. 用队列实现栈
- 两个队列,一个负责接收元素,然后将其他的元素弹出到后面
- 两个指针互换
- 删除的时候,识别队头
js
var MyStack = function() {
// 正规队列
this.queue1 = []
// 入栈队列
this.queue2 = []
// 栈长度
this.size = 0
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
// q2入栈
this.queue2.push(x)
// q1有元素就倒过去
while(this.queue1.length) {
this.queue2.push(this.queue1.shift())
}
// 交换q1和q2,确保q1是正规队列,q2是空的
let temp = this.queue2
this.queue2 = this.queue1
this.queue1 = temp
// 长度+1
this.size++
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
// 长度-1
this.size--
// q1队头出列
return this.queue1.shift()
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
return this.queue1[0]
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return this.size === 0
};
/**
* Your MyStack object will be instantiated and called as such:
* var obj = new MyStack()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.empty()
*/