622. Design Circular Queue

problem

solution

利用初始化陣列 vector<int>(k,-1);,如果數值是-1,代表該空間為空,可以assign

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
class MyCircularQueue {
private:
vector<int> nums;
int front , back, cap ;
public:
MyCircularQueue(int k) {
nums = vector<int>(k,-1);
front = 0;
back = 0;
cap = k;
}

bool enQueue(int value) {
if(isFull()) return false;
nums[back] = value;
back = (back+1)%cap;
return true;
}

bool deQueue() {
if(isEmpty()) return false;
nums[front] = -1;
front = (front+1)%cap;
return true;
}

int Front() {
if(isEmpty()) return -1;
return nums[front];
}

int Rear() {
if(isEmpty()) return -1;
return nums[(back-1+cap)%cap];
}

bool isEmpty() {
return nums[front] == -1 && (back== front);

}

bool isFull() {
return nums[back]!=-1 && (back == front);

}
};