来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-queue-using-stacks
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
说明:
进阶:
示例:
输入: ["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
提示:
class MyQueue { public MyQueue() { } public void push(int x) { } public int pop() { } public int peek() { } public boolean empty() { } } /** * 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(); */
用两个栈可以实现队列的功能,其中一个用来处理push操作,后面称为push栈;另一个用来处理pop操作,后面成为pop栈。
当做push操作的时候,就正常往push栈里面push。
当做pop操作的时候,先看pop栈是否为空,如果pop栈不为空,就从中pop出对象;如果pop栈为空的话。就将push栈内的数据依次写入pop栈,再进行弹出。
push 1 -> push[1] pop[] push 2 -> push[1,2] pop[] push 3 -> push[1,2,3] pop[] pop -> push[] pop[3,2,1] push[] pop[3,2] 弹出1
代码如下:
class MyQueue { private Stack<Integer> push = new Stack(); private Stack<Integer> pop = new Stack(); public MyQueue() { } public void push(int x) { push.push(x); } public int pop() { if (!pop.empty()) { return pop.pop(); } if (push.empty()) { return -1; } while (!push.empty()) { pop.push(push.pop()); } return pop.pop(); } public int peek() { if (!pop.empty()) { return pop.peek(); } if (push.empty()) { return -1; } while (!push.empty()) { pop.push(push.pop()); } return pop.peek(); } public boolean empty() { return push.empty() && pop.empty(); } }