forked from avinashbest/java-coding-ninjas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueUsingArrays.java
More file actions
76 lines (66 loc) · 1.68 KB
/
Copy pathQueueUsingArrays.java
File metadata and controls
76 lines (66 loc) · 1.68 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
package queues;
public class QueueUsingArrays {
private int[] data;
private int front; // index of the element @ the front end of the queue
private int rear; // index of the element @ the last end of the queue
private int size;
public QueueUsingArrays() {
data = new int[5];
front = -1;
rear = -1;
}
public QueueUsingArrays(int capacity) {
data = new int[capacity];
front = -1;
rear = -1;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void enqueue(int element) {
if (size == data.length) {
doubleCapacity();
}
if (size == 0) {
front++;
}
rear = (rear + 1) % data.length;
data[rear] = element;
size++;
}
private void doubleCapacity() {
int[] tmp = data;
data = new int[tmp.length * 2];
int index = 0;
for (int i = front; i < tmp.length; i++) {
data[index++] = tmp[i];
}
for (int i = 0; i < front - 1; i++) {
data[index++] = tmp[i];
}
front = 0;
rear = tmp.length - 1;
}
public int front() {
if (size == 0) {
throw new IllegalArgumentException("Queue is Empty");
}
return data[front];
}
public int dequeue() {
if (size == 0) {
throw new IllegalArgumentException("Queue is Empty");
}
int tmp = data[front];
front = (front + 1) % data.length;
size--;
if (size == 0) {
front = -1;
rear = -1;
}
return tmp;
}
}