-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRingBufferQueue.java
More file actions
90 lines (47 loc) · 1.63 KB
/
Copy pathRingBufferQueue.java
File metadata and controls
90 lines (47 loc) · 1.63 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
public class RingBufferQueue {
private interface RingBufferQueueDataStructure {
public boolean add(Object item);
public Object peek();
public Object remove();
}
private static class RingBufferQueue1 implements RingBufferQueueDataStructure {
Object[] items;
int size, writeIndex, used;
public RingBufferQueue1(int size) {
items = new Object[size];
this.size = size;
}
public boolean add(Object item) {
if(this.used != this.size) {
this.items[this.writeIndex] = item;
this.writeIndex = (this.writeIndex + 1) % this.size;
this.used++;
return true;
}
return false;
}
public Object peek() {
return this.items[(this.writeIndex + (this.size - this.used)) % this.size];
}
public Object remove() {
if(this.used > 0) {
Object item = peek();
this.used--;
return item;
}
return null;
}
}
public static void main(String[] args) {
RingBufferQueueDataStructure[] rbqClasses = new RingBufferQueueDataStructure[]{new RingBufferQueue1(10)};
for (RingBufferQueueDataStructure queue : rbqClasses) {
queue.add("1");
queue.add("2");
System.out.println(queue.peek());
System.out.println(queue.remove());
queue.add("3");
System.out.println(queue.remove());
System.out.println("------");
}
}
}