forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT1.java
More file actions
51 lines (44 loc) · 1.22 KB
/
T1.java
File metadata and controls
51 lines (44 loc) · 1.22 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
/**
* @program JavaBooks
* @description: 用两个栈实现队列
* @author: mf
* @create: 2020/03/11 12:12
*/
package subject.sq;
import java.util.Stack;
public class T1 {
private Stack<Integer> in;
private Stack<Integer> out;
/** Initialize your data structure here. */
public T1() {
in = new Stack<>();
out = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
in.push(x); // 输入栈,不断的push元素,没啥特殊的
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
// 弹出栈在弹出前,先判断栈是否有元素,如果为空就从in栈中导入到out栈
if(out.isEmpty()) {
while(! in.isEmpty()) {
out.push(in.pop());
}
}
return out.pop();
}
/** Get the front element. */
public int peek() {
if(out.isEmpty()) {
while(! in.isEmpty()) {
out.push(in.pop());
}
}
return out.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
}