题目描述(力扣232题):
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x)将元素 x 推到队列的末尾int pop()从队列的开头移除并返回元素int peek()返回队列开头的元素boolean empty()如果队列为空,返回true;否则,返回false
说明:
- 你 只能 使用标准的栈操作 —— 也就是只有
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类创建两个栈stack1[],stack2[]
var MyQueue = function() {
this.stack1 = [];
this.stack2 = [];
};
push操作直接通过栈的push方法加入栈stack1[]中,
MyQueue.prototype.push = function(x) {
this.stack1.push(x);
}
pop操作:思路:咱们先通过pop方法将stack1的数值全部取出来然后再通过push方法放入栈stack2中,最后通过pop方法取出stack2的顶部元素就可以了,不过这里有一个问题,就是要先判断栈stack2中是否有元素,如果有元素,此时就不能将栈stack1中的元素压过来,不然就会影响栈stack2中的元素出队列,这时候就直接通过pop方法取出stack2顶部元素并移除。
MyQueue.prototype.pop = function() {
if (this.stack2.length == 0) {
while (this.stack1.length > 0) {
this.stack2.push(this.stack1.pop());
}
}
return this.stack2.pop();
};
peek操作 咱们不能通过pop方法取出stack2的顶部元素,因为pop方法会移除元素,所以咱们可以通过指定下标来查找并返回顶部元素。
MyQueue.prototype.peek = function() {
if (this.stack2.length == 0) {
while (this.stack1.length > 0) {
this.stack2.push(this.stack1.pop());
}
}
const stack2Len=this.stack2.length
return this.stack2[stack2Len-1]
};
empty操作:判断两个栈是否都为空,都为空则返回true,否则返回false
MyQueue.prototype.empty = function() {
// if (this.stack1.length == 0 && this.stack2.length == 0) {
// return true;
// }
// return false;
return !this.stack1.length && !this.stack2.length;
};