-
Notifications
You must be signed in to change notification settings - Fork 0
/
S232.java
61 lines (50 loc) · 1.66 KB
/
S232.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
import java.util.Stack;
/**
* LC#232 Implement Queue using Stacks
* Link:https://leetcode-cn.com/problems/implement-queue-using-stacks/
* 思路:使用负负得正的思路,使用两个 Stack(inputStack,outputStack)实现队列的 FIFO 特性
*/
public class S232 {
// 初始化空栈
private Stack<Integer> inputStack = null;
private Stack<Integer> outputStack = null;
public S232() {
// 实例化再加载
inputStack = new Stack<>();
outputStack = new Stack<>();
}
public void push(int x) {
inputStack.push(x);
}
public int pop() {
// 输出栈为 null, 从输入栈获取数据
if (outputStack.isEmpty()) {
while(!inputStack.empty()) {
outputStack.push(inputStack.pop());
}
}
return outputStack.pop();
}
public int peek() {
// 输出栈为 null, 从输入栈获取数据
if(outputStack.isEmpty()) {
while(!inputStack.isEmpty()) {
outputStack.push(inputStack.pop());
}
}
return outputStack.peek();
}
public boolean empty() {
// 当两个栈为 null,当前队列 empty == true
return inputStack.isEmpty() && outputStack.isEmpty();
}
public static void main(String[] args) {
S232 solution232 = new S232();
solution232.push(1);
solution232.push(2);
solution232.push(3);
System.out.println(solution232.peek()); // accert == 1
System.out.println(solution232.pop()); // accert == 1
System.out.println(solution232.empty()); // accert == false
}
}