- Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathCircularQueue.java
More file actions
Latest commit
104 lines (93 loc) · 3.07 KB
/
Copy pathCircularQueue.java
File metadata and controls
104 lines (93 loc) · 3.07 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
importExceptions.OverflowException;
importExceptions.UnderflowException;
importjava.util.Scanner;
publicclassCircularQueue {
privateint[] queue;
privateintsize;
privateintfront;
privateintrear;
publicCircularQueue() {
queue = null;
size = 0;
front = rear = 0;
}
publicCircularQueue(intsize) {
this.size = size;
front = rear = -1;
queue = newint[size];
}
publicstaticvoidmain(String[] args) {
intch, x;
Scannersc = newScanner(System.in);
System.out.print("Enter the size of the queue : ");
intn = sc.nextInt();
n = Math.abs(n);
CircularQueueq = newCircularQueue(n);
loop:
for (; ; ) {
System.out.print("1. Enqueue\n" +
"2. Dequeue\n" +
"3. Display\n" +
"0. Exit\n" +
"Enter your choice : ");
ch = sc.nextInt();
switch (ch) {
case0:
breakloop;
case1:
System.out.print("Enter the number you want to enqueue : ");
x = sc.nextInt();
try {
q.enqueue(x);
} catch (OverflowExceptione) {
System.out.println(e.getMessage());
}
break;
case2:
try {
x = q.dequeue();
System.out.println(x + " has been removed");
} catch (UnderflowExceptione) {
System.out.println(e.getMessage());
}
break;
case3:
q.display();
break;
default:
System.out.println("Dude, seriously?\nI'm sure you can do better than that.\nTry again.");
}
System.out.println();
}
}
privatebooleanisFull() {
return (rear + 1) % size == front;
}
privatebooleanisEmpty() {
returnfront == rear;
}
publicvoidenqueue(intx) throwsOverflowException {
if (!isFull()) {
rear = (rear + 1) % size;
queue[rear] = x;
} else
thrownewOverflowException("Cannot enqueue. Queue is full");
}
publicintdequeue() throwsUnderflowException {
if (!isEmpty()) {
front = (front + 1) % size;
returnqueue[front];
} else
thrownewUnderflowException("Cannot dequeue. Queue is empty");
}
publicvoiddisplay() {
if (!isEmpty()) {
inti;
System.out.print("[");
for (i = (front + 1) % size; i != rear; i = (i + 1) % size)
System.out.print(queue[i] + ", ");
System.out.println(queue[i] + "]");
} else
System.out.println("[]");
}
}