面试题 03.04. 化栈为队
- 使用两个栈(s1,s2)进行模拟队列,入队时使用s2保存,出队时把s2栈,进行依次出栈。
- 出栈的元素依次进行入栈到s1,然后s1出栈就是正确的队列模式下应该出队的元素首位。
- 原理是利用s1可以对s2栈入队元素的逆序,就可以在外在表现上正确模拟队列的操作,先入先出。
var MyQueue = function() {
this.s1 = [];
this.s2 = [];
};
MyQueue.prototype.push = function(x) {
this.s2.push(x);
};
MyQueue.prototype.pop = function() {
this.transfer();
const ret = this.s1.pop();
return ret;
};
MyQueue.prototype.peek = function() {
this.transfer();
return this.s1[this.s1.length - 1];
};
MyQueue.prototype.empty = function() {
return this.s1.length === 0 && this.s2.length === 0;
};
MyQueue.prototype.transfer = function() {
if (this.s1.length > 0) return;
while (this.s2.length > 0){
this.s1.push(this.s2.pop());
}
};