-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayQueue.java
More file actions
80 lines (71 loc) · 1.62 KB
/
Copy pathArrayQueue.java
File metadata and controls
80 lines (71 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package Queue;
public class ArrayQueue<T> implements _Queue<T> {
public T[] arr;
public int size = 0;
//head out ,tail input
private int head = 0;
private int tail = 0;
public ArrayQueue(int capacity) {
this.arr = (T[]) new Object[capacity];
this.size = capacity;
}
/*数据搬移,然后再插入。
* */
public boolean betterAdd(T data) {
//tail no space
if (tail == size) {
//full
if (head == 0) {
return false;
}
//move to pre for save space
for (int i = head; i < tail ; i++) {
this.arr[i-head] = arr[head];
}
tail = tail-head;//tail -= head;
head = 0;
}
this.arr[tail] = data;
tail++;
return true;
}
@Override
public boolean isEmpty() {
return this.size == 0;
}
@Override
public int size() {
return this.size;
}
@Override
public boolean add(T data) {
//full
if (tail == size)
return false;
this.arr[tail] = data;
tail++;
return true;
}
@Override
public T peek() {
return this.arr[head] ;
}
@Override
public T poll() {
//empty
if (head == tail)
return null;
//head out tail input
T old = this.arr[head];
head++;
return old;
}
@Override
public void clear() {
for (int i = 0; i < this.size; i++) {
arr[i] = null;
}
this.size = 0;
this.head = this.tail = 0;
}
}