-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularQueue.java
More file actions
89 lines (80 loc) · 2.63 KB
/
CircularQueue.java
File metadata and controls
89 lines (80 loc) · 2.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
package Queue;
/**
* Traffic system: In computer controlled traffic system, circular queues are used to switch on the traffic lights one by one repeatedly as per the time set.
* CPU Scheduling: Operating systems often maintain a queue of processes that are ready to execute or that are waiting for a particular event to occur.
*/
public class CircularQueue {
public static void main(String[] args) throws Exception {
CircularQueueArray queueArray = new CircularQueueArray(4);
queueArray.add(10);
queueArray.add(20);
queueArray.add(30);
queueArray.add(40);
queueArray.display();
queueArray.remove();
queueArray.display();
queueArray.add(10);
queueArray.display();
}
public static class CircularQueueArray {
private final int[] arr;
int size;
private int rear;
private int front;
public CircularQueueArray(int size) {
arr = new int[size];
front = -1;
rear = -1;
}
// Add Function
public void add(int x) throws Exception {
if (size == arr.length) {
throw new Exception("Queue is Full!");
} else if (size == 0) {
front = rear = 0;
arr[0] = x;
} else {
rear = (rear + 1) % arr.length;
arr[rear] = x;
}
size++;
}
// Remove Function
public int remove() throws Exception {
if (size == 0) {
throw new Exception("Queue is Empty!");
} else {
int val = arr[front];
front = (front + 1) % arr.length;
size--;
return val;
}
}
// Peek Function
public int peek() throws Exception {
if (size == 0) {
throw new Exception("Queue is Empty!");
} else
return arr[front];
}
// Display Function
public void display() {
if (size == 0) {
System.out.println("Queue is Empty!");
return;
} else if (front <= rear) {
for (int i = front; i <= rear; i++) {
System.out.print(arr[i] + " ");
}
} else {
for (int i = front; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
for (int i = 0; i <= rear; i++) {
System.out.print(arr[i] + " ");
}
}
System.out.println();
}
}
}