题目
实现一个MyQueue类,该类用两个栈来实现一个队列。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
来源:力扣(LeetCode)leetcode-cn.com/problems/im…
解题思路
- 题目要求用两个栈来实现,栈的特性是先进后出。
- 那我们可以定义一个栈inStack,队列的push操作时入栈。定义一个outStack,出队列的时候从outStack出栈,如果outStack没元素了,就把inStack里的出栈后在outStack入栈,inStack的栈底元素刚好在outStack的栈顶,能满足队列的先进先出。
- 取队列首部时如果outStack不为空则取outStack第后一个元素,如果为空则去inStack的第一个元素。
- 如果两个栈都为空则队列为空。
代码实现
/**
* Initialize your data structure here.
*/
var MyQueue = function() {
//用于入队列
this.inStack = new Array()
//用于出队列
this.outStack = new Array()
};
/**
* Push element x to the back of queue.
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.inStack.push(x)
};
/**
* Removes the element from in front of queue and returns that element.
* @return {number}
*/
MyQueue.prototype.pop = function() {
if (this.outStack.length === 0) {
//如果出栈为空了则从入栈导入数据
while(this.inStack.length) {
this.outStack.push(this.inStack.pop())
}
}
return this.outStack.pop()
};
/**
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function() {
//如果出栈有元素取栈顶元素,否则取入栈的栈尾元素
if (this.outStack.length > 0)
return this.outStack[this.outStack.length - 1]
else if (this.inStack.length > 0)
return this.inStack[0]
else
return -1
};
/**
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
//两个栈都为空时队列才为空
return this.inStack.length === 0 && this.outStack.length === 0
};
如有错误欢迎指出,欢迎一起讨论!