LC.P225[用队列实现栈]

方法一:模拟

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
import java.util.Deque;

class MyStack {
Deque<Integer> q1;
Deque<Integer> q2;

public MyStack() {
q1 = new ArrayDeque<>();
q2 = new ArrayDeque<>();
}

public void push(int x) {
q2.offer(x);
while (!q1.isEmpty()) {
q2.offer(q1.poll());
}
Deque<Integer> q = q1;
q1 = q2;
q2 = q;
}

public int pop() {
return q1.poll();
}

public int top() {
return q1.peek();
}

public boolean empty() {
return q1.isEmpty();
}
}

/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$