面试题 03.04. 化栈为队

  1. class MyQueue {
  2. Deque<Integer> instack;
  3. Deque<Integer> outStack;
  4. /** Initialize your data structure here. */
  5. public MyQueue() {
  6. instack = new LinkedList<>();
  7. outStack = new LinkedList<>();
  8. }
  9. /** Push element x to the back of queue. */
  10. public void push(int x) {
  11. instack.push(x);
  12. }
  13. /** Removes the element from in front of queue and returns that element. */
  14. public int pop() {
  15. if (outStack.isEmpty()) {
  16. inToOut();
  17. }
  18. return outStack.pop();
  19. }
  20. /** Get the front element. */
  21. public int peek() {
  22. if (outStack.isEmpty()) {
  23. inToOut();
  24. }
  25. return outStack.peek();
  26. }
  27. private void inToOut() {
  28. while (!instack.isEmpty()) {
  29. outStack.push(instack.pop());
  30. }
  31. }
  32. /** Returns whether the queue is empty. */
  33. public boolean empty() {
  34. return instack.isEmpty() && outStack.isEmpty();
  35. }
  36. }
  37. /**
  38. * Your MyQueue object will be instantiated and called as such:
  39. * MyQueue obj = new MyQueue();
  40. * obj.push(x);
  41. * int param_2 = obj.pop();
  42. * int param_3 = obj.peek();
  43. * boolean param_4 = obj.empty();
  44. */