-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCircularQueue.java
68 lines (57 loc) · 1.51 KB
/
CircularQueue.java
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
package Queues;
public class CircularQueue<E> {
private Object[] arr;
private int front = -1, rear = 0;
public CircularQueue(int capacity) {
arr = new Object[capacity];
}
public boolean add(E val) throws Exception {
if (isFull()) {
throw new Exception("StackOverflow Exception");
}
if (isEmpty()) {
front = (front + 1) % arr.length;
arr[rear] = val;
rear = (rear + 1) % arr.length;
return true;
}
arr[rear] = val;
rear = (rear + 1) % arr.length;
return true;
}
public E peek() {
return (E) arr[front];
}
public E remove() throws Exception {
if (isEmpty()) {
throw new Exception("Empty Stack Exception");
}
E ret = (E) arr[front];
if ((front + 1) % arr.length == rear) {
front = -1;
return ret;
}
front = (front + 1) % arr.length;
return ret;
}
public boolean isEmpty() {
return front == -1;
}
public boolean isFull() {
return front == rear;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("[ ");
int i = front;
do {
if (!isEmpty()) {
builder.append(arr[i] + " ");
i = (i + 1) % arr.length;
}else{
break;
}
} while (i != rear);
return builder.append(']').toString();
}
}