|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | import java.util.Stack;
|
4 |
| -/**Implement the following operations of a queue using stacks. |
| 4 | +/** |
| 5 | + * 232. Implement Queue using Stacks |
| 6 | + * |
| 7 | + * Implement the following operations of a queue using stacks. |
5 | 8 |
|
6 | 9 | push(x) -- Push element x to the back of queue.
|
7 | 10 | pop() -- Removes the element from in front of queue.
|
8 | 11 | peek() -- Get the front element.
|
9 | 12 | empty() -- Return whether the queue is empty.
|
| 13 | +
|
10 | 14 | Notes:
|
11 | 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.
|
12 | 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.
|
13 |
| - You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).*/ |
| 17 | + You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). |
| 18 | + */ |
14 | 19 | public class _232 {
|
15 | 20 |
|
16 |
| - class MyQueue { |
| 21 | + public static class Solution1 { |
| 22 | + class MyQueue { |
17 | 23 |
|
18 |
| - Stack<Integer> input = new Stack(); |
19 |
| - Stack<Integer> output = new Stack(); |
| 24 | + Stack<Integer> input = new Stack(); |
| 25 | + Stack<Integer> output = new Stack(); |
20 | 26 |
|
21 |
| - // Push element x to the back of queue. |
22 |
| - public void push(int x) { |
23 |
| - input.push(x); |
24 |
| - } |
| 27 | + // Push element x to the back of queue. |
| 28 | + public void push(int x) { |
| 29 | + input.push(x); |
| 30 | + } |
25 | 31 |
|
26 |
| - // Removes the element from in front of queue. |
27 |
| - public int pop() { |
28 |
| - peek(); |
29 |
| - return output.pop(); |
30 |
| - } |
| 32 | + // Removes the element from in front of queue. |
| 33 | + public int pop() { |
| 34 | + peek(); |
| 35 | + return output.pop(); |
| 36 | + } |
31 | 37 |
|
32 |
| - // Get the front element. |
33 |
| - public int peek() { |
34 |
| - if (output.isEmpty()) { |
35 |
| - while (!input.isEmpty()) { |
36 |
| - output.push(input.pop()); |
| 38 | + // Get the front element. |
| 39 | + public int peek() { |
| 40 | + if (output.isEmpty()) { |
| 41 | + while (!input.isEmpty()) { |
| 42 | + output.push(input.pop()); |
| 43 | + } |
37 | 44 | }
|
| 45 | + return output.peek(); |
38 | 46 | }
|
39 |
| - return output.peek(); |
40 |
| - } |
41 | 47 |
|
42 |
| - // Return whether the queue is empty. |
43 |
| - public boolean empty() { |
44 |
| - return input.isEmpty() && output.isEmpty(); |
| 48 | + // Return whether the queue is empty. |
| 49 | + public boolean empty() { |
| 50 | + return input.isEmpty() && output.isEmpty(); |
| 51 | + } |
45 | 52 | }
|
46 | 53 | }
|
47 | 54 | }
|
| 55 | + |
0 commit comments