题目描述
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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(双端队列)来模拟一个栈,只要是标准的栈操作即可。
进阶:
- 你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。
示例:
输入:[“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,2,3,然后出队,再入队4,出队,整个流程如下:
- 将1,2,3入栈第一个栈,此时第一个栈为1,2,3
- 出队,按队的性质应该出1。此时第二个栈为空,于是把1,2,3出栈后入栈到第二个栈,此时第一个栈为空,第二个栈为3,2,1 (1在顶部),此时出栈即出的是1
- 入队4,将4入栈第一个栈,第一个栈变成了4,
- 出队,第二个栈不为空,出栈第二个栈的顶部元素;
代码
class MyQueue {Deque<Integer> stack1;Deque<Integer> stack2;/** Initialize your data structure here. */public MyQueue() {stack1 = new ArrayDeque<>();stack2 = new ArrayDeque<>();}/** Push element x to the back of queue. */// 入队直接入到stack1即可public void push(int x) {stack1.offerLast(x);}/** Removes the element from in front of queue and returns that element. */// 出队时先看stack2是否为空,如果不为空,则直接从stack2出栈,因为stack2中的元素的倒置过的// 所以出栈等价于出队// 如果stack2为空,则将stack1中的出栈后依次入栈到stack2中,实现倒置,然后从stack2出栈public int pop() {if (!stack2.isEmpty()) {return stack2.pollLast();} else {while (!stack1.isEmpty()) {int temp = stack1.pollLast();stack2.offerLast(temp);}return stack2.pollLast();}}/** Get the front element. */// peek和pop逻辑相同,只是一个是peekLast, 一个是pollLastpublic int peek() {if (!stack2.isEmpty()) {return stack2.peekLast();} else {while (!stack1.isEmpty()) {int temp = stack1.pollLast();stack2.offerLast(temp);}return stack2.peekLast();}}/** Returns whether the queue is empty. */// 两个栈都为空,才是空public boolean empty() {return stack1.isEmpty() && stack2.isEmpty();}}/*** Your MyQueue object will be instantiated and called as such:* MyQueue obj = new MyQueue();* obj.push(x);* int param_2 = obj.pop();* int param_3 = obj.peek();* boolean param_4 = obj.empty();*/
