|
1 | 1 | class MyQueue {
|
| 2 | + |
| 3 | + private final Stack<Integer> stackOne; |
| 4 | + private final Stack<Integer> stackTwo; |
2 | 5 |
|
3 |
| - /** Initialize your data structure here. */ |
4 |
| - Stack<Integer> stack; |
5 |
| - Stack<Integer> revStack; |
6 |
| - public MyQueue() { |
7 |
| - stack = new Stack<>(); |
8 |
| - revStack = new Stack<>(); |
9 |
| - } |
10 |
| - |
11 |
| - /** Push element x to the back of queue. */ |
12 |
| - public void push(int x) { |
13 |
| - stack.push(x); |
14 |
| - } |
15 |
| - |
16 |
| - /** Removes the element from in front of queue and returns that element. */ |
17 |
| - public int pop() { |
18 |
| - while (!stack.isEmpty()) { |
19 |
| - revStack.push(stack.pop()); |
| 6 | + public MyQueue() { |
| 7 | + this.stackOne = new Stack<>(); |
| 8 | + this.stackTwo = new Stack<>(); |
20 | 9 | }
|
21 |
| - int num = revStack.pop(); |
22 |
| - while (!revStack.isEmpty()) { |
23 |
| - stack.push(revStack.pop()); |
| 10 | + |
| 11 | + public void push(int x) { |
| 12 | + this.stackOne.push(x); |
24 | 13 | }
|
25 |
| - return num; |
26 |
| - } |
27 |
| - |
28 |
| - /** Get the front element. */ |
29 |
| - public int peek() { |
30 |
| - while (!stack.isEmpty()) { |
31 |
| - revStack.push(stack.pop()); |
| 14 | + |
| 15 | + public int pop() { |
| 16 | + exchangeElements(stackOne, stackTwo); |
| 17 | + int popped = stackTwo.pop(); |
| 18 | + exchangeElements(stackTwo, stackOne); |
| 19 | + return popped; |
32 | 20 | }
|
33 |
| - int num = revStack.peek(); |
34 |
| - while (!revStack.isEmpty()) { |
35 |
| - stack.push(revStack.pop()); |
| 21 | + |
| 22 | + public int peek() { |
| 23 | + exchangeElements(stackOne, stackTwo); |
| 24 | + int peeked = stackTwo.peek(); |
| 25 | + exchangeElements(stackTwo, stackOne); |
| 26 | + return peeked; |
| 27 | + } |
| 28 | + |
| 29 | + public boolean empty() { |
| 30 | + return stackOne.isEmpty(); |
| 31 | + } |
| 32 | + |
| 33 | + private void exchangeElements(Stack<Integer> stack1, Stack<Integer> stack2) { |
| 34 | + while (!stack1.isEmpty()) { |
| 35 | + stack2.push(stack1.pop()); |
| 36 | + } |
36 | 37 | }
|
37 |
| - return num; |
38 |
| - } |
39 |
| - |
40 |
| - /** Returns whether the queue is empty. */ |
41 |
| - public boolean empty() { |
42 |
| - return stack.isEmpty(); |
43 |
| - } |
44 | 38 | }
|
45 | 39 |
|
46 | 40 | /**
|
|
0 commit comments