题目
- 用两个栈来实现一个队列,完成队列的Push和Pop操作。
- leetcode链接:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/solution/
思想
- 栈是先进后出,队列是先进先出,因此两个栈,一个用来push,一个用来pop,同时注意下两个栈不为空的时候。
官方解法
var CQueue = function () {
this.inputStack = []
this.outputStack = []
}
/**
* @param {number} value
* @return {void}
*/
CQueue.prototype.appendTail = function (value) {
this.inputStack.push(value)
}
/**
* @return {number}
*/
CQueue.prototype.deleteHead = function () {
if (this.outputStack.length) {
return this.outputStack.pop()
} else {
while(this.inputStack.length) {
this.outputStack.push(this.inputStack.pop())
}
return this.outputStack.length ? this.outputStack.pop() : -1
}
}
/**
* Your CQueue object will be instantiated and called as such:
* var obj = new CQueue()
* obj.appendTail(value)
* var param_2 = obj.deleteHead()
*/