-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathDesign Circular Queue.cpp
81 lines (72 loc) · 1.93 KB
/
Design Circular Queue.cpp
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
class MyCircularQueue {
int head = -1;
int tail = -1;
int[] q;
int k;
public MyCircularQueue(int k) {
q = new int[k];
this.k = k;
}
public boolean enQueue(int value) {
if(head == -1 && tail == -1) {
// enqueue when the queue is empty
head = tail = 0;
q[tail] = value; // enQueue done
return true;
}
if((tail == k-1 && head == 0) || tail+1 == head) {
// queue is full
return false;
}
tail++;
if(tail == k) // condition for circularity
tail = 0;
q[tail] = value; // enQueue done
return true;
}
public boolean deQueue() {
if(head == -1) {
// check if q is already empty
return false;
}
if(head == tail) {
// only 1 element is there and head,tail both points same index
head = tail = -1; // deQueue done
return true;
}
head++; // deQueue done
if(head == k) // condition for circularity
head = 0;
return true;
}
public int Front() {
if(head == -1)
return -1;
return q[head];
}
public int Rear() {
if(tail == -1)
return -1;
return q[tail];
}
public boolean isEmpty() {
if(head == -1 && tail == -1)
return true;
return false;
}
public boolean isFull() {
if(tail == k-1 || tail+1 == head)
return true;
return false;
}
}
/**
* Your MyCircularQueue object will be instantiated and called as such:
* MyCircularQueue obj = new MyCircularQueue(k);
* boolean param_1 = obj.enQueue(value);
* boolean param_2 = obj.deQueue();
* int param_3 = obj.Front();
* int param_4 = obj.Rear();
* boolean param_5 = obj.isEmpty();
* boolean param_6 = obj.isFull();
*/