|
| 1 | +import java.util.Stack; |
| 2 | + |
| 3 | +/** |
| 4 | + * Implement the following operations of a queue using stacks. |
| 5 | + * <p> |
| 6 | + * push(x) -- Push element x to the back of queue. |
| 7 | + * pop() -- Removes the element from in front of queue. |
| 8 | + * peek() -- Get the front element. |
| 9 | + * empty() -- Return whether the queue is empty. |
| 10 | + * <p> |
| 11 | + * Notes: |
| 12 | + * 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. |
| 13 | + * 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. |
| 14 | + * You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). |
| 15 | + * <p> |
| 16 | + * Created by drfish on 6/8/2017. |
| 17 | + */ |
| 18 | +public class _232ImplementQueueUsingStacks { |
| 19 | + public class MyQueue { |
| 20 | + private Stack<Integer> stack1; |
| 21 | + private Stack<Integer> stack2; |
| 22 | + |
| 23 | + /** |
| 24 | + * Initialize your data structure here. |
| 25 | + */ |
| 26 | + public MyQueue() { |
| 27 | + stack1 = new Stack<>(); |
| 28 | + stack2 = new Stack<>(); |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Push element x to the back of queue. |
| 33 | + */ |
| 34 | + public void push(int x) { |
| 35 | + stack1.push(x); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Removes the element from in front of queue and returns that element. |
| 40 | + */ |
| 41 | + public int pop() { |
| 42 | + if (stack2.isEmpty()) { |
| 43 | + while (!stack1.isEmpty()) { |
| 44 | + stack2.push(stack1.pop()); |
| 45 | + } |
| 46 | + } |
| 47 | + return stack2.pop(); |
| 48 | + |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Get the front element. |
| 53 | + */ |
| 54 | + public int peek() { |
| 55 | + if (stack2.isEmpty()) { |
| 56 | + while (!stack1.isEmpty()) { |
| 57 | + stack2.push(stack1.pop()); |
| 58 | + } |
| 59 | + } |
| 60 | + return stack2.peek(); |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * Returns whether the queue is empty. |
| 65 | + */ |
| 66 | + public boolean empty() { |
| 67 | + return stack1.isEmpty() && stack2.isEmpty(); |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments