-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheasy_232.java
More file actions
39 lines (38 loc) · 993 Bytes
/
easy_232.java
File metadata and controls
39 lines (38 loc) · 993 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 232. Implement Queue using Stacks
public class MyQueue {
private Stack<Integer> inputStack;
private Stack<Integer> outputStack;
public MyQueue() {
inputStack = new Stack<>();
outputStack = new Stack<>();
}
public void push(int x) {
inputStack.push(x);
}
public int pop() {
transferIfNeeded();
return outputStack.pop();
}
public int peek() {
transferIfNeeded();
return outputStack.peek();
}
public boolean empty() {
return inputStack.empty() && outputStack.empty();
}
private void transferIfNeeded() {
if (outputStack.empty()) {
while (!inputStack.empty()) {
outputStack.push(inputStack.pop());
}
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/