-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularQueue.java
More file actions
84 lines (73 loc) · 1.98 KB
/
Copy pathCircularQueue.java
File metadata and controls
84 lines (73 loc) · 1.98 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
public class CircularQueue {
public static void main(String[] args) {
queue myQueue = new queue(6);
myQueue.addInQueue(1);
myQueue.addInQueue(2);
myQueue.addInQueue(3);
myQueue.addInQueue(4);
//print the elements in the queue
System.out.println("Elements in the queue:");
if (!myQueue.isEmpty()) {
int i = myQueue.front;
while (true) {
System.out.print(myQueue.arr[i] + " ");
if (i == myQueue.rear) break;
i = (i + 1) % myQueue.size;
}
}
System.out.println();
}
static class queue {
int arr[];
int front;
int rear;
int size;
// constructor
queue(int size) {
this.size = size;
this.front = -1;
this.rear = -1;
this.arr = new int[size];
}
// add element
public void addInQueue(int data){
if(isFull()){
System.out.println("Queue is Full");
return;
}
if(front == -1) {
// First element
front = 0;
rear = 0;
} else {
rear = (rear+1)%size;
}
arr[rear] = data;
}
//delete element
public void delete(){
if(isEmpty()){
System.out.println("Queue is Empty");
return;
}
if(front == rear){
// Only one element was present
front = -1;
rear = -1;
}else{
front = (front+1) % size;
}
}
// isEmpty
public boolean isEmpty(){
return (front == -1 && rear == -1);
}
//isfull
public boolean isFull(){
if(((rear+1) % size) == front){
return true;
}
return false;
}
}
}