题目描述
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
分析
栈的特点是先进后出,队列的特点是先进先出。
单栈无法实现队列功能: 栈底元素(对应队首元素)无法直接删除,需要将上方所有元素出栈。push,pop。
将stack1作为入队栈,stack2作为出队栈。注意出入顺序。举个简单的例子,防止出错,比如:123,45分两次入队。出队顺序就是12345. 首先将stack1放入123,再将stack1当中的元素以头元素开始放入stack2中。
代码实现
var CQueue = function() {
this.stack1=[]//入队栈
this.stack2=[]//出队栈
};
/**
* @param {number} value
* @return {void}
*/
CQueue.prototype.appendTail = function(value) {
this.stack1.push(value)
};
/**
* @return {number}
*/
CQueue.prototype.deleteHead = function() {
while(this.stack1.length){
this.stack2.push(this.stack1.shift())
}
if(this.stack2.length){
return this.stack2.shift()
}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()
*/
var CQueue = function() {
this.stack1=[]
this.stack2=[]
};
/**
* @param {number} value
* @return {void}
*/
CQueue.prototype.appendTail = function(value) {
this.stack1.push(value)
};
/**
* @return {number}
*/
CQueue.prototype.deleteHead = function() {
if(this.stack2.length){
return this.stack2.pop()
}else{
while(this.stack1.length){
this.stack2.push(this.stack1.pop())
}
}
if(this.stack2.length){
return this.stack2.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()
*/