-
Notifications
You must be signed in to change notification settings - Fork 151
/
Copy pathEx_1_3_38.java
110 lines (92 loc) · 2.11 KB
/
Ex_1_3_38.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
103
104
105
106
107
108
109
110
package Ch_1_3;
import edu.princeton.cs.algs4.StdOut;
import java.util.Iterator;
import tools.PrintUtil;
/**
* Created by HuGuodong on 2019/7/27.
*/
public class Ex_1_3_38 {
public static class ArrayBasedGeneralizeQueue<Item> implements Iterable<Item> {
Item[] a;
int first;
int last;
int N;
public ArrayBasedGeneralizeQueue() {
a = (Item[]) new Object[2];
}
public void resize(int cap) {
Item[] copy = (Item[]) new Object[cap];
for (int i = 0; i < N; i++) {
copy[i] = a[(first + i) % a.length];
}
first = 0;
last = N;
a = copy;
}
public int size() {
return N;
}
public boolean isEmpty() {
return N == 0;
}
public void insert(Item x) {
if (N == a.length) {
resize(2 * a.length);
}
a[last++] = x;
if (last == a.length) {
last = 0;
}
N++;
}
public Item delete(int k) {
Item cur = a[(first + k - 1) % a.length];
// move
for (int i = k; i < N; i++) {
a[(first + i - 1) % a.length] = a[(first + i) % a.length];
}
N--;
last = last - 1;
if (last == -1) {
last = a.length - 1;
}
a[last] = null;
if (N > 0 && N == a.length / 4) {
resize(a.length / 2);
}
return cur;
}
public class ArrayIterator implements Iterator<Item> {
int start = first;
int cnt = 0;
int size = N;
@Override
public boolean hasNext() {
return cnt < N;
}
@Override
public Item next() {
Item item = a[(start++) % a.length];
cnt++;
return item;
}
}
@Override
public Iterator<Item> iterator() {
return new ArrayIterator();
}
}
public static void main(String[] args) {
ArrayBasedGeneralizeQueue<Integer> q = new ArrayBasedGeneralizeQueue<>();
for (int i = 0; i < 10; i++) {
q.insert(i);
}
PrintUtil.show(q);
StdOut.println(q.delete(1));
StdOut.println(q.delete(1));
StdOut.println(q.delete(1));
q.insert(10);
q.delete(6);
PrintUtil.show(q);
}
}