-
Notifications
You must be signed in to change notification settings - Fork 151
/
Copy pathEx_1_3_48.java
102 lines (82 loc) · 1.63 KB
/
Ex_1_3_48.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package Ch_1_3;
import Ch_1_3.Ex_1_3_33._Deque;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by HuGuodong on 2019/8/5.
*/
public class Ex_1_3_48 {
public static class LeftStack<Item> {
private _Deque<Item> de;
public int N;
public LeftStack(_Deque<Item> de) {
this.de = de;
}
public void push(Item item) {
de.pushLeft(item);
N++;
}
public Item pop() {
if (isEmpty()) {
return null;
}
N--;
return de.popLeft();
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
}
public static class RightStack<Item> {
private _Deque<Item> de;
public int N;
public RightStack(_Deque<Item> de) {
this.de = de;
}
public void push(Item item) {
de.pushRight(item);
N++;
}
public Item pop() {
if (isEmpty()) {
return null;
}
N--;
return de.popRight();
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
}
public static void main(String[] args) {
_Deque<Integer> de = new _Deque<>();
LeftStack<Integer> leftStack = new LeftStack<>(de);
for (int i = 0; i < 5; i++) {
leftStack.push(i);
}
while (!leftStack.isEmpty()) {
StdOut.println(leftStack.pop());
}
RightStack<Integer> rightStack = new RightStack<>(de);
for (int i = 5; i < 10; i++) {
rightStack.push(i);
}
while (!rightStack.isEmpty()) {
StdOut.println(rightStack.pop());
}
// 4
// 3
// 2
// 1
// 0
// 9
// 8
// 7
// 6
}
}