-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathCircularQueue.java
More file actions
64 lines (54 loc) · 1.39 KB
/
CircularQueue.java
File metadata and controls
64 lines (54 loc) · 1.39 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
package struct.queue;
/**
* 循环队列
*
* @param <T>
*/
public class CircularQueue<T> {
// items 表示数组,capacity 表示数组大小
private T[] items;
private int capacity;
// head表示队头下标,tail表示队尾下标
private int head;
private int tail;
public CircularQueue(int capacity) {
this.capacity = capacity;
this.items = (T[]) new Object[this.capacity];
}
public boolean enqueue(T data) {
// 队列满了
if ((tail + 1) % capacity == head) {
return false;
}
items[tail] = data;
tail = (tail + 1) % capacity;
return true;
}
public T dequeue() {
if (head == tail) {
return null;
}
T value = items[head];
head = (head + 1) % capacity;
return value;
}
public void printAll() {
if (capacity == 0) {
return;
}
for (int i = head; (i % capacity) != tail; i++) {
System.out.print(items[i] + ",");
}
System.out.println();
}
public static void main(String[] args) {
CircularQueue<Integer> queue = new CircularQueue<>(8);
for (int i = 1; i <= 8; i++) {
queue.enqueue(i);
}
queue.printAll();
for (int i = 0; i < 8; i++) {
System.out.println(queue.dequeue());
}
}
}