https://leetcode-cn.com/problems/implement-queue-using-stacks/

    1. class MyQueue {
    2. Stack<Integer> stack1;
    3. Stack<Integer> stack2;
    4. public MyQueue() {
    5. stack1 = new Stack<>();
    6. stack2 = new Stack<>();
    7. }
    8. public void push(int x) {
    9. // 1. S1 的全部元素进入 S2
    10. while (!stack1.isEmpty()){
    11. stack2.push(stack1.pop());
    12. }
    13. // 2. 将新元素压入 S1
    14. stack1.push(x);
    15. // 3. 再将 S2 中元素依次压入 S1
    16. while (!stack2.isEmpty()){
    17. stack1.push(stack2.pop());
    18. }
    19. }
    20. public int pop() {
    21. return stack1.pop();
    22. }
    23. public int peek() {
    24. return stack1.peek();
    25. }
    26. public boolean empty() {
    27. return stack1.isEmpty();
    28. }
    29. }