Skip to content

Commit 712e924

Browse files
authored
Merge pull request #82 from shubhamSM1298/main
Circular Queue
2 parents 4c27349 + e79ed8d commit 712e924

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

DesignCircularQueue.java

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
//Design Circular Queue
2+
3+
class MyCircularQueue {
4+
5+
private int[] data;
6+
private int head;
7+
private int tail;
8+
private int size;
9+
10+
/** Initialize your data structure here. Set the size of the queue to be k. */
11+
public MyCircularQueue(int k) {
12+
data = new int[k];
13+
head = -1;
14+
tail = -1;
15+
size = k;
16+
}
17+
18+
/** Insert an element into the circular queue. Return true if the operation is successful. */
19+
public boolean enQueue(int value) {
20+
if (isFull() == true) {
21+
return false;
22+
}
23+
if (isEmpty() == true) {
24+
head = 0;
25+
}
26+
tail = (tail + 1) % size;
27+
data[tail] = value;
28+
return true;
29+
}
30+
31+
/** Delete an element from the circular queue. Return true if the operation is successful. */
32+
public boolean deQueue() {
33+
if (isEmpty() == true) {
34+
return false;
35+
}
36+
if (head == tail) {
37+
head = -1;
38+
tail = -1;
39+
return true;
40+
}
41+
head = (head + 1) % size;
42+
return true;
43+
}
44+
45+
/** Get the front item from the queue. */
46+
public int Front() {
47+
if (isEmpty() == true) {
48+
return -1;
49+
}
50+
return data[head];
51+
}
52+
53+
/** Get the last item from the queue. */
54+
public int Rear() {
55+
if (isEmpty() == true) {
56+
return -1;
57+
}
58+
return data[tail];
59+
}
60+
61+
/** Checks whether the circular queue is empty or not. */
62+
public boolean isEmpty() {
63+
return head == -1;
64+
}
65+
66+
/** Checks whether the circular queue is full or not. */
67+
public boolean isFull() {
68+
return ((tail + 1) % size) == head;
69+
}
70+
}
71+
72+
/**
73+
* Your MyCircularQueue object will be instantiated and called as such:
74+
* MyCircularQueue obj = new MyCircularQueue(k);
75+
* boolean param_1 = obj.enQueue(value);
76+
* boolean param_2 = obj.deQueue();
77+
* int param_3 = obj.Front();
78+
* int param_4 = obj.Rear();
79+
* boolean param_5 = obj.isEmpty();
80+
* boolean param_6 = obj.isFull();
81+
*/

0 commit comments

Comments
 (0)