LC.P232[用栈实现队列]

方法一:模拟

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
40
41
42
class MyQueue {

Deque<Integer> s1;
Deque<Integer> s2;

public MyQueue() {
s1 = new ArrayDeque<>();
s2 = new ArrayDeque<>();
}

public void push(int x) {
s1.push(x);
}

public int pop() {
int x = peek();
s2.pop();
return x;
}

public int peek() {
if (!s2.isEmpty()) return s2.peek();
if (s1.isEmpty()) return -1;
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
return s2.peek();
}

public boolean empty() {
return s1.isEmpty() && s2.isEmpty();
}
}

/**
* 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();
*/
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$