题目
解题
本题与 LeetCode《程序员面试金典》面试题 03.04. 化栈为队 几乎一样,面试题 03.04 还多实现了 peek 和 empty 方法,详细思路不赘述了,指路上面的链接。
力扣官网解答的动图演示:用两个栈实现队列
// javascript
var CQueue = function() {
this.inStack = [];
this.outStack = [];
};
/**
* @param {number} value
* @return {void}
*/
CQueue.prototype.appendTail = function(value) {
this.inStack.push(value);
};
/**
* @return {number}
*/
CQueue.prototype.deleteHead = function() {
if (this.outStack.length === 0) {
while (this.inStack.length > 0) {
this.outStack.push(this.inStack.pop());
}
}
// 如果仍然为空,说明队列里没有元素,返回 -1
return this.outStack.length > 0 ? this.outStack.pop() : -1;
};