-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKQueue.java
95 lines (76 loc) · 2.34 KB
/
KQueue.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
package gfg.ds.queue;
import java.util.Arrays;
/**
* This method requires some extra space. Space may not be an issue because queue items are
* typically large, for example, queues of employees, students, etc where every item is of hundreds
* of bytes. For usch large queues, the extra space used is comparatively very less as we use three
* integer arrays as extra space.
*
* @noinspection WeakerAccess
*/
public class KQueue {
private int[] arr, front, rear, next;
private int free;
public KQueue(int queues, int size) {
assert queues <= size;
arr = new int[size];
front = new int[queues];
rear = new int[queues];
next = new int[size];
free = 0;
Arrays.fill(front, -1);
Arrays.fill(rear, -1);
for (int i = 0; i < size - 1; i++) {
next[i] = i + 1;
}
}
/** t=O(1) */
public void enqueue(int queueNo, int data) {
assert !isFull() : "Queue is full";
assert queueNo >= 0 && queueNo < front.length : "Invalid queue no";
int toBeInsertedIndex = free;
free = next[free];
if (front[queueNo] == -1) {
front[queueNo] = toBeInsertedIndex;
} else {
next[rear[queueNo]] = toBeInsertedIndex;
}
next[toBeInsertedIndex] = -1;
rear[queueNo] = toBeInsertedIndex;
arr[toBeInsertedIndex] = data;
}
/** t=O(1) */
public int dequeue(int queueNo) {
assert !isEmpty(queueNo) : "Queue is empty";
assert queueNo >= 0 && queueNo < front.length : "Invalid queue no";
int toBeDeletedIndex = front[queueNo];
next[toBeDeletedIndex] = free;
free = toBeDeletedIndex;
front[queueNo] = next[toBeDeletedIndex];
if (front[queueNo] == -1) {
rear[queueNo] = -1;
}
return arr[toBeDeletedIndex];
}
/** t=O(1) */
public int front(int queueNo) {
assert !isEmpty(queueNo) : "Queue is empty";
assert queueNo >= 0 && queueNo < front.length : "Invalid queue no";
return arr[front[queueNo]];
}
/** t=O(1) */
public int rear(int queueNo) {
assert !isEmpty(queueNo) : "Queue is empty";
assert queueNo >= 0 && queueNo < front.length : "Invalid queue no";
return arr[rear[queueNo]];
}
/** t=O(1) */
public boolean isFull() {
return free == -1;
}
/** t=O(1) */
public boolean isEmpty(int queueNo) {
assert queueNo >= 0 && queueNo < front.length : "Invalid queue no";
return front[queueNo] == -1;
}
}