-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTwoStackQueue.java
More file actions
58 lines (50 loc) · 1.41 KB
/
TwoStackQueue.java
File metadata and controls
58 lines (50 loc) · 1.41 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
package stack_and_queue;
import java.util.Stack;
/**
* @Author: Wenhang Chen
* @Description:由两个栈实现的队列
* @Date: Created in 9:55 10/28/2019
* @Modified by:
*/
public class TwoStackQueue {
public Stack<Integer> stackPush;
public Stack<Integer> stackPop;
public TwoStackQueue() {
stackPush = new Stack<>();
stackPop = new Stack<>();
}
// push栈向pop栈倒入数据
private void pushToPop() {
if (stackPop.empty()) {
while (!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
}
public void add(int pushInt) {
stackPush.push(pushInt);
}
public int poll() {
if (stackPush.empty() && stackPop.empty()) {
throw new RuntimeException("Queue is empty!");
}
pushToPop();
return stackPop.pop();
}
public int peek() {
if (stackPush.empty() && stackPop.empty()) {
throw new RuntimeException("Queue is empty!");
}
pushToPop();
return stackPop.peek();
}
public static void main(String[] args) {
TwoStackQueue twoStackQueue = new TwoStackQueue();
twoStackQueue.add(1);
twoStackQueue.add(2);
System.out.println(twoStackQueue.poll());
System.out.println(twoStackQueue.poll());
twoStackQueue.add(3);
System.out.println(twoStackQueue.poll());
}
}