forked from guokaide/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularQueue.java
More file actions
69 lines (59 loc) · 1.57 KB
/
Copy pathCircularQueue.java
File metadata and controls
69 lines (59 loc) · 1.57 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
package queue;
public class CircularQueue<T> {
private T[] items;
private int capacity;
private int head;
private int tail;
public CircularQueue(int capacity) {
this.capacity = capacity;
this.items = (T[]) new Object[capacity];
this.head = 0;
this.tail = 0;
}
// T(N)=O(1)
public boolean enqueue(T item) {
// 队满条件
if ((tail + 1) % capacity == head) {
return false;
}
items[tail] = item;
tail = (tail + 1) % capacity;
return true;
}
// T(N)=O(1)
public T dequeue() {
// 队空条件
if (head == tail) {
return null;
}
T tmp = items[head];
items[head] = null; // 这里可以选择置为nulL,也可以不置为null.
head = (head + 1) % capacity;
return tmp;
}
// for test
public void printAll() {
System.out.print("[");
for (int i = 0; i < capacity; i++) {
System.out.print(items[i] + " ");
}
System.out.print("]");
System.out.println();
}
public static void main(String[] args) {
CircularQueue<java.lang.String> queue = new CircularQueue<>(4);
queue.printAll();
queue.enqueue("A");
queue.printAll();
queue.enqueue("B");
queue.enqueue("C");
queue.enqueue("D");
queue.printAll();
queue.enqueue("E");
queue.printAll();
queue.dequeue();
queue.dequeue();
queue.enqueue("E");
queue.printAll();
}
}