Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。
一.题目
232. 用栈实现队列 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(
push、pop、peek、empty): 实现MyQueue类:
void push(int x)将元素 x 推到队列的末尾int pop()从队列的开头移除并返回元素void push(int x)将元素 x 推到队列的末尾int pop()从队列的开头移除并返回元素 说明:- 你 只能 使用标准的栈操作 —— 也就是只有
push to top,peek/pop from top,size, 和is empty操作是合法的。 - 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。 示例 1:
输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]
解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
提示:
1 <= x <= 9- 最多调用
100次push、pop、peek和empty - 假设所有操作都是有效的 (例如,一个空的队列不会调用
pop或者peek操作)
二、思路分析:
跟着题目的要求走,要求我们不能够使用其他的方式而只能用栈的常规操作来完成题目的要求,题目给出两个栈来实现队列的相关操作。那么我们就可以利用两个栈来实现队列的入队和出队,首先我们将一个栈当作最基本的入队操作,即如果有入队操作那么直接往第一个栈中压入即可。
如果有出队操作的时候,我们就需要把当前的第一个栈的元素全部压入第二个栈,那么第一个出来的正好与队列第一个出来的相匹配(前提是第二个栈中没有元素),如果第二个栈中有元素的话我们出队操作就直接将第二个栈中的栈顶元素弹出即可。
三、代码:
var MyQueue = function () {
this.list1 = []
this.list2 = []
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function (x) {
this.list1.push(x)
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function () {
this.peek()
return this.list2.pop()
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function () {
if (!this.list2.length) {
while (this.list1.length !== 0) {
this.list2.push(this.list1.pop())
}
}
return this.list2[this.list2.length - 1]
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function () {
return !this.list1.length && !this.list2.length
};
四、总结:
用栈实现队列的操作其实特别简单,思路也很清晰,但是这种问题觉得在JS中就大可不必,因为JS的很多函数都能实现这些操作非常方便0.0