题目
题目描述:
方法:双栈
思路
栈是先进后出,队列是先进先出。用两个栈,一个栈管进入的元素,用于 push 操作,一个栈把进入的元素的顺序调整成队列的顺序,用于 pop 和 peek 操作。
代码
JavaScript
var MyQueue = function() {
this.inStack = [];
this.outStack = [];
}
MyQueue.prototype.push = function(x) {
this.inStack.push(x);
}
MyQueue.prototype.pop = function() {
if(!this.outStack.length) {
this.in2out();
}
return this.outStack.pop();
}
MyQueue.prototype.peek = function() {
if (!this.outStack.length) {
this.in2out();
}
return this.outStack[this.outStack.length - 1];
}
MyQueue.prototype.empty = function() {
return this.inStack.length === 0 && this.outStack.length === 0
}
MyQueue.prototype.in2out = function() {
while(this.inStack.length) {
this.outStack.push(this.inStack.pop())
}
}
复杂度分析
| 时间复杂度 | 空间复杂度 |
|---|---|
O(1) | O(n) |
push 和 empty 为 O(1),pop 和 peek 为均摊 O(1),对于每个元素,至多入栈和出栈各两次 | n 是操作总数 |