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