-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCircularQueue.java
76 lines (65 loc) · 1.49 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
69
70
71
72
73
74
75
import java.util.Arrays;
import java.util.NoSuchElementException;
public class CircularQueue<T> {
private T[]arr;
private int size, head=-1,tail=-1;
public CircularQueue() {
arr=(T[])new Object[5];
}
public CircularQueue(int initialCapacity) {
arr=(T[])new Object[initialCapacity];
}
public boolean isFull(){
return size==arr.length;
}
public boolean isEmpty(){
return size==0;
}
public void insureCapacity(){
T[]copy= Arrays.copyOf(arr,2*size);
arr=copy;
}
public void enqueue(T value){
if(isFull())
insureCapacity();
if(head==-1)
head=0;
tail=(tail+1)% arr.length;
arr[tail]=value;
size++;
}
public T dequeue(){
if(isEmpty())
throw new NoSuchElementException();
T removedVal=arr[head];
head=(head+1)% arr.length;
size--;
return removedVal;
}
public T element(){
if(isEmpty())
throw new NoSuchElementException();
return arr[head];
}
@Override
public String toString() {
String str="";
for(int i=0,cur=head;i<size;i++){
str+=arr[cur]+" ";
cur=(cur+1)%arr.length;
}
return str;
}
public T[] getArr() {
return arr;
}
public int getSize() {
return size;
}
public int getHead() {
return head;
}
public int getTail() {
return tail;
}
}