- Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathQueue.java
More file actions
Latest commit
103 lines (92 loc) · 2.93 KB
/
Copy pathQueue.java
File metadata and controls
103 lines (92 loc) · 2.93 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
importExceptions.OverflowException;
importExceptions.UnderflowException;
importjava.util.Scanner;
publicclassQueue {
privateint[] queue;
privateintsize;
privateintfront;
privateintrear;
publicQueue() {
queue = null;
size = 0;
front = rear = -1;
}
publicQueue(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();
Queueq = newQueue(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() {
returnrear >= size - 1;
}
privatebooleanisEmpty() {
returnfront > rear;
}
publicvoidenqueue(intx) throwsOverflowException {
if (front == -1)
++front;
if (!isFull())
queue[++rear] = x;
else
thrownewOverflowException("Queue is full. Unable to enqueue");
}
publicintdequeue() throwsUnderflowException {
if (isEmpty()) {
thrownewUnderflowException("Queue is empty. Unable to dequeue");
}
returnqueue[front++];
}
publicvoiddisplay() {
if (isEmpty()) {
System.out.println("Queue is empty");
return;
}
System.out.print("[");
for (inti = front; i < rear; i++)
System.out.print(queue[i] + ", ");
System.out.println(queue[rear] + "]");
}
}