-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path622-Design-Circular-Queue.js
70 lines (57 loc) · 1.26 KB
/
622-Design-Circular-Queue.js
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
/**
* @param {number} k
*/
class MyCircularQueue {
constructor(k) {
this.capacity = k;
this.items = Array(k).fill(null);
this.head = 0;
this.tail = 0;
}
/**
* @param {number} value
* @return {boolean}
*/
enQueue(value) {
if (this.isFull()) return false;
this.items[this.tail] = value;
this.tail = (this.tail + 1) % this.capacity;
return true;
}
/**
* @return {boolean}
*/
deQueue() {
if (this.isEmpty()) return false;
this.items[this.head] = null;
this.head = (this.head + 1) % this.capacity;
return true;
}
/**
* @return {number}
*/
Front() {
if (this.isEmpty()) return -1;
return this.items[this.head];
}
/**
* @return {number}
*/
Rear() {
if (this.isEmpty()) return -1;
const rear = (this.tail + this.capacity - 1) % this.capacity;
return this.items[rear];
}
/**
* @return {boolean}
*/
isEmpty() {
return this.head === this.tail && this.items[this.head] === null;
}
/**
* @return {boolean}
*/
isFull() {
return this.head === this.tail && this.items[this.head] !== null;
}
}