腾讯&剑指offer09:用两个栈实现队列
sisterAn opened this issue · 3 comments
sisterAn commented
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]示例 2:
输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]提示:
1 <= values <= 10000- 最多会对
appendTail、deleteHead进行10000次调用
code-byte-labs commented
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 if (this.stack1.length) {
while(this.stack1.length) {
this.stack2.push(this.stack1.pop())
}
return this.stack2.pop();
} else {
return -1
}
};sisterAn commented
解题思路:
- 栈后进先出,队列先进先出
- 双栈可以实现序列倒置:假设有
stack1=[1, 2, 3]、stack2=[],如果循环出栈stack1并将出栈元素进栈stack2,则循环结束后,stack1=[]、stack2=[3, 2, 1],即通过stack2实现了stack1中元素的倒置 - 当需要删除队首元素时,仅仅需要
stack2出栈即可;当stack2为空时,出队就需要将stack1元素倒置倒stack2,stack2再出队即可;如果stack1也为空,即队列中没有元素,返回-1
代码实现:
const CQueue = function() {
this.stack1 = []
this.stack2 = []
};
CQueue.prototype.appendTail = function(value) {
this.stack1.push(value)
};
CQueue.prototype.deleteHead = function() {
if(this.stack2.length) {
return this.stack2.pop()
}
if(!this.stack1.length) return -1
while(this.stack1.length) {
this.stack2.push(this.stack1.pop())
}
return this.stack2.pop()
};复杂度分析:
- 时间复杂度:
appendTail的时间复杂度为O(1),deleteHead的时间复杂度为 O(n) - 空间复杂度:O(n)
dinjufen commented
var CQueue = function() {
this.s = [];
this.t = [];
};
/**
* @param {number} value
* @return {void}
*/
CQueue.prototype.appendTail = function(value) {
this.s.push(value);
};
/**
* @return {number}
*/
CQueue.prototype.deleteHead = function() {
if (this.t.length > 0) {
return this.t.pop();
} else {
while (this.s.length > 0) {
this.t.push(this.s.pop());
}
if (this.t.length > 0) {
return this.t.pop();
}
}
return -1;
};