-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution225.java
More file actions
executable file
·66 lines (59 loc) · 1.61 KB
/
Copy pathSolution225.java
File metadata and controls
executable file
·66 lines (59 loc) · 1.61 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.*;
class MyStack {
private Deque<Integer> stack1;
private Deque<Integer> stack2;
public MyStack() {
stack1 = new ArrayDeque<>();
stack2 = new ArrayDeque<>();
}
public void push(int x) {
if (stack1.isEmpty())
stack2.add(x);
else stack1.add(x);
}
public int pop() {
int len1 = stack1.size(), len2 = stack2.size();
if (stack1.isEmpty()) {
for (int i = 0; i < len2 - 1; i++) {
stack1.add(stack2.remove());
}
return stack2.remove();
}
else {
for (int i = 0; i < len1 - 1; i++) {
stack2.add(stack1.remove());
}
return stack1.remove();
}
}
public int top() {
int res;
int len1 = stack1.size(), len2 = stack2.size();
if (stack1.isEmpty()) {
for (int i = 0; i < len2 - 1; i++) {
stack1.add(stack2.remove());
}
res = stack2.peek();
stack1.add(stack2.remove());
}
else {
for (int i = 0; i < len1 - 1; i++) {
stack2.add(stack1.remove());
}
res = stack1.peek();
stack2.add(stack1.remove());
}
return res;
}
public boolean empty() {
return stack1.isEmpty() && stack2.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();
*/