-
Notifications
You must be signed in to change notification settings - Fork 0
/
232.java
102 lines (83 loc) · 2.05 KB
/
232.java
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
class MyQueue {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public MyQueue() {
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
changeStackStatus();
return stack2.pop();
}
public int peek() {
changeStackStatus();
return stack2.peek();
}
public boolean empty() {
return stack1.isEmpty() && stack2.isEmpty();
}
private void changeStackStatus(){
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
int temp = stack1.pop();
stack2.push(temp);
}
}
}
}
/**
* 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();
*/
// 第二次自己做的版本
class MyQueue {
private Stack<Integer> stackA;
private Stack<Integer> stackB;
public MyQueue() {
stackA = new Stack<>();
stackB = new Stack<>();
}
public void push(int x) {
stackA.push(x);
}
public int pop() {
while(!stackA.isEmpty()){
stackB.push(stackA.peek());
stackA.pop();
}
int peek = stackB.pop();
while(!stackB.isEmpty()){
stackA.push(stackB.peek());
stackB.pop();
}
return peek;
}
public int peek() {
while(!stackA.isEmpty()){
stackB.push(stackA.peek());
stackA.pop();
}
int peek = stackB.peek();
while(!stackB.isEmpty()){
stackA.push(stackB.peek());
stackB.pop();
}
return peek;
}
public boolean empty() {
return stackA.isEmpty() && stackB.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();
*/