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