-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularQueue.java
More file actions
67 lines (57 loc) · 1.44 KB
/
CircularQueue.java
File metadata and controls
67 lines (57 loc) · 1.44 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
package ds.queue;
/**
* @author xiangdotzhaoAtwoqutechcommacom
* @date 2019/11/19
* <p>
* 循环队列
*/
public class CircularQueue implements IQueue {
private String[] items;
private int n = 0;
private int head = 0;
private int tail = 0;
public CircularQueue(int capacity) {
items = new String[capacity];
n = capacity;
}
public static void main(String[] args) {
CircularQueue circularQueue = new CircularQueue(6);
circularQueue.enqueue("1");
circularQueue.enqueue("2");
circularQueue.enqueue("3");
circularQueue.enqueue("4");
circularQueue.enqueue("5");
circularQueue.enqueue("6");
circularQueue.printAll();
circularQueue.dequeue();
circularQueue.printAll();
}
@Override
public boolean enqueue(String item) {
if ((tail + 1) % n == head) {
return false;
}
items[tail] = item;
tail = (tail + 1) % n;
return true;
}
@Override
public String dequeue() {
if (head == tail) {
return null;
}
String ret = items[head];
head = (head + 1) % n;
return ret;
}
@Override
public void printAll() {
if (n == 0) {
return;
}
for (int i = head; i % n != tail; i = (i + 1) % n) {
System.out.print(items[i] + " ");
}
System.out.println();
}
}