leetcode 225 The reverse of leetcode 232. This time is using two stacks to simulate the operations of Queue. We can also use just one stack to get the work done, however, I think, simple is the best, isn't it? The draft paper: import java.util.Stack; public class MyQueue { private Stack<Integer> stackIn; private Stack<Integer> stackOut; public MyQueue() { stackIn = new Stack<>(); stackOut = new Stack<>(); } public void push(int x) { stackIn.push(x); } public int pop() { if (stackOut.empty()) { dumpStackInToOut(); } return stackOut.pop(); } public int peek() { if (stackOut.empty()) { dumpStackInToOut(); } return stackOut.peek(); } public boolean empty() { return stackIn.empty() && stackOut.empty(); } public void dumpStackInToOut() { while (!stackIn.isEmpty()) { stackOut.push(stackIn.pop()); } } public static void main(String[] args) { var queue = new MyQueue(); queue.push(1); queue.push(2); System.out.println(queue.pop()); queue.push(3); queue.push(4); System.out.println(queue.pop()); System.out.println(queue.pop()); System.out.println(queue.pop()); System.out.println(queue.empty()); } } #leetcode leetcode 225 http://fanyfull.github.io/2022/07/31/leetcode-225/ 作者 Fany Full 发布于 2022年7月31日 许可协议 leetcode 20 上一篇 leetcode 232 下一篇 Please enable JavaScript to view the comments