-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularQueue.java
More file actions
46 lines (39 loc) · 966 Bytes
/
Copy pathCircularQueue.java
File metadata and controls
46 lines (39 loc) · 966 Bytes
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
import java.util.*;
/*
* 1. Dropbox ppt
* 2. http://cs-technotes.blogspot.com/2010/11/thread-safe-circular-queue.html
*/
public class CircularQueue<T> {
int capacity;
T[] data;
int head;
int tail;
int size;
public CircularQueue(int n) {
capacity = n;
data = (T[]) new Object[n];
head = tail = 0;
size = 0;
}
public boolean isEmpty() {
return size() == 0;
}
public int size() {
return size;
}
public T peek() {
if (isEmpty()) throw new NoSuchElementException();
return data[head];
}
public synchronized void offer(T t) {
if (size() == capacity) throw new RuntimeException("full");
data[(head+size)%capacity] = t;
size++;
}
public synchronized T poll() {
if (isEmpty()) throw new NoSuchElementException();
T ret = data[head];
head = (head+1)%capacity;
return ret;
}
}