|
1 | 1 | packagecom.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | importjava.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 | publicclass_232 {
|
15 | 20 |
|
16 |
| -classMyQueue { |
| 21 | +publicstaticclassSolution1 { |
| 22 | +classMyQueue { |
17 | 23 |
|
18 |
| -Stack<Integer>input =newStack(); |
19 |
| -Stack<Integer>output =newStack(); |
| 24 | +Stack<Integer>input =newStack(); |
| 25 | +Stack<Integer>output =newStack(); |
20 | 26 |
|
21 |
| -// Push element x to the back of queue. |
22 |
| -publicvoidpush(intx) { |
23 |
| -input.push(x); |
24 |
| - } |
| 27 | +// Push element x to the back of queue. |
| 28 | +publicvoidpush(intx) { |
| 29 | +input.push(x); |
| 30 | +} |
25 | 31 |
|
26 |
| -// Removes the element from in front of queue. |
27 |
| -publicintpop() { |
28 |
| -peek(); |
29 |
| -returnoutput.pop(); |
30 |
| - } |
| 32 | +// Removes the element from in front of queue. |
| 33 | +publicintpop() { |
| 34 | +peek(); |
| 35 | +returnoutput.pop(); |
| 36 | +} |
31 | 37 |
|
32 |
| -// Get the front element. |
33 |
| -publicintpeek() { |
34 |
| -if (output.isEmpty()) { |
35 |
| -while (!input.isEmpty()) { |
36 |
| -output.push(input.pop()); |
| 38 | +// Get the front element. |
| 39 | +publicintpeek() { |
| 40 | +if (output.isEmpty()) { |
| 41 | +while (!input.isEmpty()) { |
| 42 | +output.push(input.pop()); |
| 43 | + } |
37 | 44 | }
|
| 45 | +returnoutput.peek(); |
38 | 46 | }
|
39 |
| -returnoutput.peek(); |
40 |
| - } |
41 | 47 |
|
42 |
| -// Return whether the queue is empty. |
43 |
| -publicbooleanempty() { |
44 |
| -returninput.isEmpty() &&output.isEmpty(); |
| 48 | +// Return whether the queue is empty. |
| 49 | +publicbooleanempty() { |
| 50 | +returninput.isEmpty() &&output.isEmpty(); |
| 51 | + } |
45 | 52 | }
|
46 | 53 | }
|
47 | 54 | }
|
| 55 | + |