非独立思考

    1. class MyQueue {
    2. Stack<Integer> inStack;
    3. Stack<Integer> outStack;
    4. /**
    5. * Initialize your data structure here.
    6. */
    7. public MyQueue() {
    8. inStack = new Stack<>();
    9. outStack = new Stack<>();
    10. }
    11. /**
    12. * Push element x to the back of queue.
    13. */
    14. public void push(int x) {
    15. // push进入的是inStack
    16. inStack.push(x);
    17. }
    18. /**
    19. * Removes the element from in front of queue and returns that element.
    20. */
    21. public int pop() {
    22. // pop前要先检查:
    23. // 如果outStack中还有元素,需要等它先pop完毕才能加入新值
    24. // 要将inStack里的元素一次性放入outStack
    25. if (outStack.isEmpty()) {
    26. in2out();
    27. }
    28. return outStack.pop();
    29. }
    30. /**
    31. * Get the front element.
    32. */
    33. public int peek() {
    34. // pop前要先检查:
    35. // 如果outStack中还有元素,需要等它先pop完毕才能加入新值
    36. // 要将inStack里的元素一次性放入outStack
    37. if (outStack.isEmpty()) {
    38. in2out();
    39. }
    40. return outStack.peek();
    41. }
    42. /**
    43. * Returns whether the queue is empty.
    44. */
    45. public boolean empty() {
    46. return inStack.empty() && outStack.empty();
    47. }
    48. private void in2out() {
    49. while (!inStack.empty()) {
    50. outStack.push(inStack.pop());
    51. }
    52. }
    53. }