算法实现之化栈为队
题目描述
实现一个MyQueue类,该类用两个栈来实现一个队列。
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
解题思路:
使用两个栈来实现一个队列,
一个作为输入栈,每次元素入栈(push)的时候都是添加入输入栈中;
一个作为输出栈,
每次pop元素的时候或者peek,如果输出栈中为空,
则把输入栈内的元素依次弹出并进入输出栈,然后进行出栈的操作,符合队列的先进先出原则
然后判断队列是否为空时,就判断两个栈内是否还有元素即可
点击查看代码
var MyQueue = function() {
this.inStack = [] //输入栈
this.outStack = [] //输出栈
};
// 新添加的元素全都加入输入栈中
MyQueue.prototype.push = function(x) {
this.inStack.push(x)
};
//删除元素时,当输出栈为空时,先把输入栈中的元素一次弹出并添加入输出栈中
<!-- 然后正常出栈即可 -->
MyQueue.prototype.pop = function() {
if(!this.outStack.length) {
while(this.inStack.length) {
this.outStack.push(this.inStack.pop())
}
}
return this.outStack.pop()
};
<!-- 与pop类似,但最后返回的是栈顶元素 -->
MyQueue.prototype.peek = function() {
if(!this.outStack.length) {
while(this.inStack.length) {
this.outStack.push(this.inStack.pop())
}
}
return this.outStack[this.outStack.length - 1]
};
<!-- 两个栈都为空则这个队列就是空的 -->
MyQueue.prototype.empty = function() {
return !this.inStack.length && !this.outStack.length
};

浙公网安备 33010602011771号