Implement Queue using Stacks

mplement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.

Notes:

    • You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
    • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
    • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
       1 class MyQueue {
       2     Stack<Integer> stack1 = new Stack<>();
       3     Stack<Integer> stack2 = new Stack<>();
       4     public void push(int x) {
       5         stack1.push(x);
       6     }
       7 
       8     // Removes the element from in front of queue.
       9     public void pop() {
      10         if (stack2.isEmpty()) {
      11             while(!stack1.isEmpty()) {
      12                 stack2.push(stack1.pop());
      13             }
      14         }
      15         stack2.pop();
      16     }
      17 
      18     // Get the front element.
      19     public int peek() {
      20         if (stack2.isEmpty()) {
      21             while(!stack1.isEmpty()) {
      22                 stack2.push(stack1.pop());
      23             }
      24         }
      25         return stack2.peek();
      26     }
      27 
      28     // Return whether the queue is empty.
      29     public boolean empty() {
      30         return stack1.isEmpty() && stack2.isEmpty();
      31     }
      32 }

       

posted @ 2016-05-09 20:16  YuriFLAG  阅读(148)  评论(0)    收藏  举报