题目:
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
思路:
我们用数组的push(),pop()方法模拟入栈和出栈。
1、定义两个栈,调用appendTail直接从栈1入栈就行。
2、出栈的时候先判断栈2是否有元素,如果有就先pop出去。
3、如果栈2没有元素,把栈1的全部元素都pop到栈2,再从栈2pop一个出去。
4、如果栈1和栈2都没有元素return -1
代码:
<script type="text/javascript">
var CQueue = function(){
this.zhan1 = []
this.zhan2 = []
}
CQueue.prototype.appendTail = function(value){
this.zhan1.push(value)
}
CQueue.prototype.deleteHead = function(){
if(this.zhan1.length == 0 && this.zhan2.length == 0){return -1}
if(this.zhan2.length == 0){
while(this.zhan1.length!=0){
this.zhan2.push(this.zhan1.pop())
}
}
return this.zhan2.pop()
}
var c = new CQueue()
console.log(c.deleteHead())
c.appendTail(1)
c.appendTail(2)
console.log(c.deleteHead())
c.appendTail(3)
console.log(c.deleteHead())
console.log(c.deleteHead())
</script>