-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0641-design-circular-deque.js
More file actions
73 lines (65 loc) · 1.79 KB
/
0641-design-circular-deque.js
File metadata and controls
73 lines (65 loc) · 1.79 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
/**
* Design Circular Deque
* Time Complexity: O(1)
* Space Complexity: O(k)
*/
var MyCircularDeque = function (capacityLimit) {
this.bufferStorage = new Array(capacityLimit);
this.maxSize = capacityLimit;
this.headPtr = 0;
this.tailPtr = -1;
this.itemCount = 0;
};
MyCircularDeque.prototype.insertFront = function (itemValue) {
if (this.itemCount === this.maxSize) {
return false;
}
this.headPtr = (this.headPtr - 1 + this.maxSize) % this.maxSize;
this.bufferStorage[this.headPtr] = itemValue;
this.itemCount++;
if (this.itemCount === 1) {
this.tailPtr = this.headPtr;
}
return true;
};
MyCircularDeque.prototype.insertLast = function (dataValue) {
const isFullStatus = this.isFull();
if (isFullStatus) {
return false;
}
this.tailPtr = (this.tailPtr + 1) % this.maxSize;
this.bufferStorage[this.tailPtr] = dataValue;
this.itemCount++;
return true;
};
MyCircularDeque.prototype.deleteFront = function () {
if (this.isEmpty()) return false;
this.headPtr = (this.headPtr + 1) % this.maxSize;
this.itemCount--;
return true;
};
MyCircularDeque.prototype.deleteLast = function () {
const checkEmptyState = this.itemCount === 0;
if (checkEmptyState) {
return false;
}
this.tailPtr = (this.tailPtr - 1 + this.maxSize) % this.maxSize;
this.itemCount--;
return true;
};
MyCircularDeque.prototype.getFront = function () {
if (this.itemCount === 0) {
return -1;
}
return this.bufferStorage[this.headPtr];
};
MyCircularDeque.prototype.getRear = function () {
const emptyCondition = this.isEmpty();
return emptyCondition ? -1 : this.bufferStorage[this.tailPtr];
};
MyCircularDeque.prototype.isEmpty = function () {
return this.itemCount === 0;
};
MyCircularDeque.prototype.isFull = function () {
return this.itemCount === this.maxSize;
};