|
1 | 1 | class MyQueue {
|
2 |
| - |
3 |
| - private final Stack<Integer> stackOne; |
4 |
| - private final Stack<Integer> stackTwo; |
| 2 | + |
| 3 | + private final Stack<Integer> first; |
| 4 | + private final Stack<Integer> second; |
5 | 5 |
|
6 | 6 | public MyQueue() {
|
7 |
| - this.stackOne = new Stack<>(); |
8 |
| - this.stackTwo = new Stack<>(); |
| 7 | + this.first = new Stack<>(); |
| 8 | + this.second = new Stack<>(); |
9 | 9 | }
|
10 | 10 |
|
11 | 11 | public void push(int x) {
|
12 |
| - this.stackOne.push(x); |
| 12 | + first.push(x); |
13 | 13 | }
|
14 | 14 |
|
15 | 15 | public int pop() {
|
16 |
| - exchangeElements(stackOne, stackTwo); |
17 |
| - int popped = stackTwo.pop(); |
18 |
| - exchangeElements(stackTwo, stackOne); |
19 |
| - return popped; |
| 16 | + move(first, second); |
| 17 | + int result = second.pop(); |
| 18 | + move(second, first); |
| 19 | + return result; |
20 | 20 | }
|
21 | 21 |
|
22 | 22 | public int peek() {
|
23 |
| - exchangeElements(stackOne, stackTwo); |
24 |
| - int peeked = stackTwo.peek(); |
25 |
| - exchangeElements(stackTwo, stackOne); |
26 |
| - return peeked; |
| 23 | + move(first, second); |
| 24 | + int result = second.peek(); |
| 25 | + move(second, first); |
| 26 | + return result; |
27 | 27 | }
|
28 | 28 |
|
29 | 29 | public boolean empty() {
|
30 |
| - return stackOne.isEmpty(); |
| 30 | + return first.isEmpty(); |
31 | 31 | }
|
32 |
| - |
33 |
| - private void exchangeElements(Stack<Integer> stack1, Stack<Integer> stack2) { |
34 |
| - while (!stack1.isEmpty()) { |
35 |
| - stack2.push(stack1.pop()); |
| 32 | + |
| 33 | + private void move(Stack<Integer> from, Stack<Integer> to) { |
| 34 | + while (!from.isEmpty()) { |
| 35 | + to.push(from.pop()); |
36 | 36 | }
|
37 | 37 | }
|
38 | 38 | }
|
|
0 commit comments