-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoStackQueue.java
More file actions
60 lines (50 loc) · 1.62 KB
/
TwoStackQueue.java
File metadata and controls
60 lines (50 loc) · 1.62 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
package stackAndqueue;
import org.junit.Test;
import java.util.Stack;
/**
* Created by LXF on 2016/7/25.
*/
public class TwoStackQueue {
private Stack<Integer> stackPush = new Stack();
private Stack<Integer> stackPop = new Stack();
public TwoStackQueue() {
}
public void add(int newNum) {
this.stackPush.push(newNum);
}
public int poll() {
if (this.stackPush.isEmpty() && this.stackPop.isEmpty()) {
throw new RuntimeException("THE QUEUE IS EMPTY");
} else {
if (this.stackPop.empty()) {
while (!this.stackPush.empty()) {
this.stackPop.push(this.stackPush.pop());
}
}
return ((Integer) this.stackPop.pop()).intValue();
}
}
public int peek() {
if (this.stackPush.isEmpty() && this.stackPop.isEmpty()) {
throw new RuntimeException("THE QUEUE IS EMPTY");
} else {
if (this.stackPop.isEmpty()) {
while (!this.stackPush.isEmpty()) {
this.stackPop.push(this.stackPush.pop());
}
}
return ((Integer) this.stackPop.peek()).intValue();
}
}
@Test
public void test() {
TwoStackQueue twoStackQueue = new TwoStackQueue();
twoStackQueue.add(1);
twoStackQueue.add(6);
twoStackQueue.add(8);
System.out.println("验证peek()方法:" + twoStackQueue.peek());
twoStackQueue.poll();
System.out.println("验证poll()方法:" + twoStackQueue.poll());
System.out.println(twoStackQueue.peek());
}
}