两个栈模拟一个队列
思路
对于js来说,意味着只能使用push()和pop()方法,不能使用shift()方法。
入队操作,直接压入入队栈(push)即可。
出队操作需要优先检查出队栈是否有数据:
若有,直接出栈。(pop)
若无,需要从入队栈倒入(push)后再出栈(pop)。
代码
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());
}
}
if(this.outStack.length>0){
return this.outStack.pop();
}else{
return -1;
}
};
/**
* Your CQueue object will be instantiated and called as such:
* var obj = new CQueue()
* obj.appendTail(value)
* var param_2 = obj.deleteHead()
*/