Advertisement
Guest User

232. Implement Queue using Stacks

a guest
Feb 17th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. class MyQueue {
  2.    
  3.     Stack<Integer> input;
  4.     Stack<Integer> output;
  5.  
  6.     /** Initialize your data structure here. */
  7.     public MyQueue() {
  8.         input = new Stack<Integer>();
  9.         output = new Stack<Integer>();
  10.     }
  11.    
  12.     /** Push element x to the back of queue. */
  13.     public void push(int x) {
  14.         input.push(x);
  15.     }
  16.    
  17.     /** Removes the element from in front of queue and returns that element. */
  18.     public int pop() {
  19.         peek();
  20.         return output.pop();
  21.     }
  22.    
  23.     /** Get the front element. */
  24.     public int peek() {
  25.         if (output.isEmpty()) {
  26.             while (!input.isEmpty()) {
  27.                 output.push(input.pop());
  28.             }
  29.         }
  30.         return output.peek();
  31.     }
  32.    
  33.     /** Returns whether the queue is empty. */
  34.     public boolean empty() {
  35.         return input.isEmpty() && output.isEmpty();
  36.     }
  37. }
  38.  
  39. /**
  40.  * Your MyQueue object will be instantiated and called as such:
  41.  * MyQueue obj = new MyQueue();
  42.  * obj.push(x);
  43.  * int param_2 = obj.pop();
  44.  * int param_3 = obj.peek();
  45.  * boolean param_4 = obj.empty();
  46.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement