-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0622_Design-Circular-Queue.cpp
More file actions
75 lines (66 loc) · 1.5 KB
/
0622_Design-Circular-Queue.cpp
File metadata and controls
75 lines (66 loc) · 1.5 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
class MyCircularQueue {
public:
int head;
int tail;
int capacity;
vector<int> q;
public:
int legalize(int x) {
x %= capacity;
return x;
}
MyCircularQueue(int k) {
head = -1;
tail = -1;
q.resize(k, -1);
capacity = k;
}
bool enQueue(int value) {
// move tail, tail++
if (isFull())
return false;
if (isEmpty()) {
head = tail = 0;
q[tail] = value;
} else {
tail++;
tail = legalize(tail);
q[tail] = value;
}
return true;
}
bool deQueue() {
// move head, --head
if (isEmpty())
return false;
if (head == tail) {
head = tail = -1;
return true;
}
head++;
head = legalize(head);
return true;
}
int Front() {
if (isEmpty())
return -1;
return q[head];
}
int Rear() {
if (isEmpty())
return -1;
return q[tail];
}
bool isEmpty() { return head == -1 && tail == -1; }
bool isFull() { return legalize(tail + 1) == head; }
};
/**
* Your MyCircularQueue object will be instantiated and called as such:
* MyCircularQueue* obj = new MyCircularQueue(k);
* bool param_1 = obj->enQueue(value);
* bool param_2 = obj->deQueue();
* int param_3 = obj->Front();
* int param_4 = obj->Rear();
* bool param_5 = obj->isEmpty();
* bool param_6 = obj->isFull();
*/