-
Notifications
You must be signed in to change notification settings - Fork 57
/
javaQueue.java
104 lines (86 loc) · 2.38 KB
/
javaQueue.java
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
public class QueueArrayApp {
public static void main(String[] args) {
QueueArray x = new QueueArray(5);
x.enqueue(2);
x.enqueue(8);
x.enqueue(3);
x.display();
try {
x.dequeue();
x.display();
x.enqueue(23);
x.enqueue(45);
x.enqueue(59);
x.enqueue(89);
x.display();
x.dequeue();
x.display();
x.enqueue(99);
System.out.println(x.peek());
x.display();
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
class QueueArray {
private int maxSize;
private int[] queArray;
private int front;
private int rear;
private int nItems;
public QueueArray(int s) {
this.queArray = new int[s];
this.maxSize = s;
this.front = 0;
this.rear = -1;
this.nItems = 0;
}
public boolean isEmpty() {
return this.nItems == 0;
}
public boolean isFull() {
return this.nItems == this.maxSize;
}
public int size() {
return this.nItems;
}
public void enqueue(int value) {
if (isFull()) {
System.out.println("Queue is Full.Insertion Terminated");
return;
}
rear = (rear + 1) % maxSize;
queArray[rear] = value;
nItems++;
}
public int dequeue() throws Exception {
if (isEmpty()) {
throw new Exception("Nothing to delete. Deletion Terminated");
}
int removedItem = this.queArray[front];
front = (front + 1) % maxSize;
nItems--;
return removedItem;
}
public int peek() throws Exception {
if (isEmpty()) {
throw new Exception("Queue is Empty. Cannot get peek value");
}
return this.queArray[this.front];
}
public void display() {
if(isEmpty()) {
System.out.println("Queue is Empty. Nothing to Print");
return;
}
System.out.println();
System.out.println("Items in the Array : ");
int i = this.front;
while (i != rear) {
System.out.print(queArray[i] + " ");
i = (i + 1) % maxSize;
}
System.out.print(queArray[rear]);
System.out.println();
}