CircleQueue.java
2.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
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
111
112
113
114
115
116
package com.bsth.data.gpsdata.analyse;
import java.util.Arrays;
/**
* 循环队列
* Created by panzhao on 2016/12/23.
*/
public class CircleQueue<T> {
/**
* (循环队列)数组的容量
*/
public int capacity;
/**
* 数组:保存循环队列的元素
*/
public Object[] elementData;
/**
* 队头(先进先出)
*/
public int head = 0;
/**
* 队尾
*/
public int tail = 0;
/**
* 以指定长度的数组来创建循环队列
*
* @param initSize
*/
public CircleQueue(final int initSize) {
capacity = initSize;
elementData = new Object[capacity];
}
/**
* 获取循环队列的大小(包含元素的个数)
*/
public int size() {
if (isEmpty()) {
return 0;
} else if (isFull()) {
return capacity;
} else {
return tail + 1;
}
}
/**
* 插入队尾一个元素
*/
public void add(final T element) {
if (isEmpty()) {
elementData[0] = element;
} else if (isFull()) {
elementData[head] = element;
head++;
tail++;
head = head == capacity ? 0 : head;
tail = tail == capacity ? 0 : tail;
} else {
elementData[tail + 1] = element;
tail++;
}
}
public boolean isEmpty() {
return tail == head && tail == 0 && elementData[tail] == null;
}
public boolean isFull() {
return head != 0 && head - tail == 1 || head == 0 && tail == capacity - 1;
}
public void clear() {
Arrays.fill(elementData, null);
head = 0;
tail = 0;
}
/**
* @return 取 循环队列里的值(先进的index=0)
*/
public Object[] getQueue() {
final Object[] elementDataSort = new Object[capacity];
final Object[] elementDataCopy = elementData.clone();
if (isEmpty()) {
} else if (isFull()) {
int indexMax = capacity;
int indexSort = 0;
for (int i = head; i < indexMax;) {
elementDataSort[indexSort] = elementDataCopy[i];
indexSort++;
i++;
if (i == capacity) {
i = 0;
indexMax = head;
}
}
} else {
for (int i = 0; i < tail; i++) {
elementDataSort[i] = elementDataCopy[i];
}
}
return elementDataSort;
}
public T getTail(){
return elementData[tail] == null?null:(T)elementData[tail];
}
}