Repository navigation
Expand file tree
/
Copy pathCircularQueue.java
More file actions
executable file
·80 lines (72 loc) · 1.94 KB
/
Copy pathCircularQueue.java
File metadata and controls
executable file
·80 lines (72 loc) · 1.94 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
package com.interview.stackqueue;
public class CircularQueue<T> {
private int QUEUE_LENGTH;
private T data[] = null;
public CircularQueue(int size){
this.QUEUE_LENGTH = size;
data = (T [])new Object[QUEUE_LENGTH];
}
private int top=-1;
private int end = -1;
public void offer(T t){
if(top == -1){
data[0] = t;
top =0;
end = 0;
}else if(top == (end + 1) % QUEUE_LENGTH){
throw new IllegalArgumentException();
}else{
end = (end + 1) % QUEUE_LENGTH;
data[end] = t;
}
}
public T top(){
if(top == -1){
throw new IllegalArgumentException();
}else{
return data[top];
}
}
public T poll(){
if(top == -1){
throw new IllegalArgumentException();
}else if(top == end){
T t = data[top];
top = -1;
end = -1;
return t;
}
else{
T t = data[top];
top = (top +1)% QUEUE_LENGTH;
return t;
}
}
public boolean isEmpty(){
if(top == -1){
return true;
}
return false;
}
public boolean isFull(){
if(top == (end + 1)% QUEUE_LENGTH){
return true;
}
return false;
}
public static void main(String args[]){
CircularQueue<Integer> circularQueue = new CircularQueue<Integer>(5);
circularQueue.offer(1);
circularQueue.offer(2);
circularQueue.offer(3);
System.out.println(circularQueue.poll());
circularQueue.offer(4);
circularQueue.offer(5);
System.out.print(circularQueue.isFull());
circularQueue.offer(6);
System.out.print(circularQueue.isFull());
while(!circularQueue.isEmpty()){
System.out.println(circularQueue.poll());
}
}
}