|
| 1 | +import java.util.LinkedList; |
| 2 | +import java.util.Queue; |
| 3 | + |
| 4 | +/** |
| 5 | + * Implement the following operations of a stack using queues. |
| 6 | + * <p> |
| 7 | + * push(x) -- Push element x onto stack. |
| 8 | + * pop() -- Removes the element on top of the stack. |
| 9 | + * top() -- Get the top element. |
| 10 | + * empty() -- Return whether the stack is empty. |
| 11 | + * <p> |
| 12 | + * Notes: |
| 13 | + * You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid. |
| 14 | + * Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue. |
| 15 | + * You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack). |
| 16 | + * <p> |
| 17 | + * Credits: |
| 18 | + * Special thanks to @jianchao.li.fighter for adding this problem and all test cases. |
| 19 | + * <p> |
| 20 | + * Created by drfish on 6/8/2017. |
| 21 | + */ |
| 22 | +public class _225ImplementStackUsingQueues { |
| 23 | + public class MyStack { |
| 24 | + private Queue<Integer> queue; |
| 25 | + |
| 26 | + /** |
| 27 | + * Initialize your data structure here. |
| 28 | + */ |
| 29 | + public MyStack() { |
| 30 | + queue = new LinkedList<>(); |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Push element x onto stack. |
| 35 | + */ |
| 36 | + public void push(int x) { |
| 37 | + queue.add(x); |
| 38 | + for (int i = 0; i < queue.size() - 1; i++) { |
| 39 | + queue.add(queue.poll()); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Removes the element on top of the stack and returns that element. |
| 45 | + */ |
| 46 | + public int pop() { |
| 47 | + return queue.poll(); |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * Get the top element. |
| 52 | + */ |
| 53 | + public int top() { |
| 54 | + return queue.peek(); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Returns whether the stack is empty. |
| 59 | + */ |
| 60 | + public boolean empty() { |
| 61 | + return queue.isEmpty(); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments