|
| 1 | +package by.andd3dfx.collections; |
| 2 | + |
| 3 | +import java.util.ArrayDeque; |
| 4 | +import java.util.Deque; |
| 5 | + |
| 6 | +/** |
| 7 | + * <pre> |
| 8 | + * <a href="https://leetcode.com/problems/implement-queue-using-stacks/description/">Task description</a> |
| 9 | + * |
| 10 | + * Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions |
| 11 | + * of a normal queue (push, peek, pop, and empty). |
| 12 | + * |
| 13 | + * Implement the MyQueue class: |
| 14 | + * void push(int x) Pushes element x to the back of the queue. |
| 15 | + * int pop() Removes the element from the front of the queue and returns it. |
| 16 | + * int peek() Returns the element at the front of the queue. |
| 17 | + * boolean empty() Returns true if the queue is empty, false otherwise. |
| 18 | + * |
| 19 | + * Notes: |
| 20 | + * You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, |
| 21 | + * and is empty operations are valid. |
| 22 | + * Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or |
| 23 | + * deque (double-ended queue) as long as you use only a stack's standard operations. |
| 24 | + * |
| 25 | + * Example 1: |
| 26 | + * Input |
| 27 | + * ["MyQueue", "push", "push", "peek", "pop", "empty"] |
| 28 | + * [[], [1], [2], [], [], []] |
| 29 | + * Output |
| 30 | + * [null, null, null, 1, 1, false] |
| 31 | + * |
| 32 | + * Explanation |
| 33 | + * MyQueue myQueue = new MyQueue(); |
| 34 | + * myQueue.push(1); // queue is: [1] |
| 35 | + * myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) |
| 36 | + * myQueue.peek(); // return 1 |
| 37 | + * myQueue.pop(); // return 1, queue is [2] |
| 38 | + * myQueue.empty(); // return false |
| 39 | + * </pre> |
| 40 | + */ |
| 41 | +public class QueueUsing2Stacks { |
| 42 | + |
| 43 | + private final Deque<Integer> stack1; |
| 44 | + private final Deque<Integer> stack2; |
| 45 | + |
| 46 | + public QueueUsing2Stacks() { |
| 47 | + stack1 = new ArrayDeque<>(); |
| 48 | + stack2 = new ArrayDeque<>(); |
| 49 | + } |
| 50 | + |
| 51 | + public void push(int x) { |
| 52 | + while (!stack2.isEmpty()) { |
| 53 | + stack1.push(stack2.pop()); |
| 54 | + } |
| 55 | + stack1.push(x); |
| 56 | + } |
| 57 | + |
| 58 | + public int pop() { |
| 59 | + while (!stack1.isEmpty()) { |
| 60 | + stack2.push(stack1.pop()); |
| 61 | + } |
| 62 | + return stack2.pop(); |
| 63 | + } |
| 64 | + |
| 65 | + public int peek() { |
| 66 | + while (!stack1.isEmpty()) { |
| 67 | + stack2.push(stack1.pop()); |
| 68 | + } |
| 69 | + return stack2.peek(); |
| 70 | + } |
| 71 | + |
| 72 | + public boolean empty() { |
| 73 | + return stack1.isEmpty() && stack2.isEmpty(); |
| 74 | + } |
| 75 | +} |
0 commit comments