维护一个 in,out 栈表示进出顺序,实现一个从 in 到 out 的转移方法。

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
class MyQueue {

private Stack<Integer> in, out;

MyQueue() {
in = new Stack<>();
out = new Stack<>();
}

void push(int val) {
in.push(val);
}

int pop() {
transferIfEmpty();
return out.pop();
}

int peek() {
transferIfEmpty();
return out.peek();
}

boolean isEmpty() {
return in.isEmpty() && out.empty();
}

private void transferIfEmpty() {
if(out.empty()) {
while(!in.empty()) {
out.push(in.pop());
}
}
}
}