- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTwoStackQueue.java
More file actions
Latest commit
58 lines (50 loc) · 1.41 KB
/
Copy pathTwoStackQueue.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
packagestack_and_queue;
importjava.util.Stack;
/**
* @Author: Wenhang Chen
* @Description:由两个栈实现的队列
* @Date: Created in 9:55 10/28/2019
* @Modified by:
*/
publicclassTwoStackQueue {
publicStack<Integer> stackPush;
publicStack<Integer> stackPop;
publicTwoStackQueue() {
stackPush = newStack<>();
stackPop = newStack<>();
}
// push栈向pop栈倒入数据
privatevoidpushToPop() {
if (stackPop.empty()) {
while (!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
}
publicvoidadd(intpushInt) {
stackPush.push(pushInt);
}
publicintpoll() {
if (stackPush.empty() && stackPop.empty()) {
thrownewRuntimeException("Queue is empty!");
}
pushToPop();
returnstackPop.pop();
}
publicintpeek() {
if (stackPush.empty() && stackPop.empty()) {
thrownewRuntimeException("Queue is empty!");
}
pushToPop();
returnstackPop.peek();
}
publicstaticvoidmain(String[] args) {
TwoStackQueuetwoStackQueue = newTwoStackQueue();
twoStackQueue.add(1);
twoStackQueue.add(2);
System.out.println(twoStackQueue.poll());
System.out.println(twoStackQueue.poll());
twoStackQueue.add(3);
System.out.println(twoStackQueue.poll());
}
}