题目介绍
实现一个MyQueue类,该类用两个栈来实现一个队列。
示例
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
- 你只能使用标准的栈操作 -- 也就是只有
push to top,peek/pop from top,size和is empty操作是合法的。 - 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
- 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
面试题 03.04. 化栈为队
b站视频
解题思路
题目比较简单,要求我们使用两个栈来模拟队列的功能,我们需要明确的一点是:栈是先进后出,队列是先进先出
1.我们使用两个数组模拟栈,一个用于模拟入队操作,一个用于模拟出队操作,入队只能在入队栈中进行,出队只能在出队栈中进行
2.当出队栈为空时,我们需要将入队栈中的元素按进入顺序反转到出队栈中(反转之后先进入的元素在最上方,每次从最上方弹出元素,即先进先出),然后从出队栈按顺序弹出元素
解题代码
/**
* Initialize your data structure here.
*/
var MyQueue = function() {
this.inStack = []
this.outStack = []
};
/**
* 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.empty()) return
if (!this.outStack.length) {
this.move()
}
return this.outStack.pop()
};
/**
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function() {
if (this.empty()) return
if (!this.outStack.length) {
this.move()
}
return this.outStack[this.outStack.length - 1]
};
/**
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return !this.inStack.length && !this.outStack.length
};
MyQueue.prototype.move = function() {
while (this.inStack.length) {
this.outStack.push(this.inStack.pop())
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* var obj = new MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/
以上就是本题的解题思路,欢迎查看我的其他文章
[路飞]_环形链表
[路飞]_环形链表II
[路飞]_快乐数
[路飞]_反转链表
[路飞]_反转链表II
[路飞]_K 个一组翻转链表
[路飞]_旋转链表
[路飞]_两两交换链表中的节点
[路飞]_最近的请求次数
[路飞]_第 k 个数
[路飞]_亲密字符串
[路飞]_柠檬水找零
[路飞]_煎饼排序
[路飞]_任务调度器