|
| 1 | +import java.util.Stack; |
| 2 | + |
| 3 | +/** |
| 4 | + * This implements Queue using two Stacks. |
| 5 | + * |
| 6 | + * Big O Runtime: |
| 7 | + * insert(): O(1) |
| 8 | + * remove(): O(1) amortized |
| 9 | + * isEmpty(): O(1) |
| 10 | + * |
| 11 | + * A queue data structure functions the same as a real world queue. |
| 12 | + * The elements that are added first are the first to be removed. |
| 13 | + * New elements are added to the back/rear of the queue. |
| 14 | + * |
| 15 | + * @author sahilb2 |
| 16 | + * |
| 17 | + */ |
| 18 | +class QueueUsingTwoStacks { |
| 19 | + |
| 20 | + // Stack to keep track of elements inserted into the queue |
| 21 | + private Stack inStack; |
| 22 | + // Stack to keep track of elements to be removed next in queue |
| 23 | + private Stack outStack; |
| 24 | + |
| 25 | + /** |
| 26 | + * Constructor |
| 27 | + */ |
| 28 | + public QueueUsingTwoStacks() { |
| 29 | + this.inStack = new Stack(); |
| 30 | + this.outStack = new Stack(); |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Inserts an element at the rear of the queue |
| 35 | + * |
| 36 | + * @param x element to be added |
| 37 | + */ |
| 38 | + public void insert(Object x) { |
| 39 | + // Insert element into inStack |
| 40 | + this.inStack.push(x); |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Remove an element from the front of the queue |
| 45 | + * |
| 46 | + * @return the new front of the queue |
| 47 | + */ |
| 48 | + public Object remove() { |
| 49 | + if(this.outStack.isEmpty()) { |
| 50 | + // Move all elements from inStack to outStack (preserving the order) |
| 51 | + while(!this.inStack.isEmpty()) { |
| 52 | + this.outStack.push( this.inStack.pop() ); |
| 53 | + } |
| 54 | + } |
| 55 | + return this.outStack.pop(); |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * Returns true if the queue is empty |
| 60 | + * |
| 61 | + * @return true if the queue is empty |
| 62 | + */ |
| 63 | + public boolean isEmpty() { |
| 64 | + return (this.inStack.isEmpty() && this.outStack.isEmpty()); |
| 65 | + } |
| 66 | + |
| 67 | +} |
0 commit comments