[LeetCode] Design Circular Deque

641. Design Circular Deque

Design your implementation of the circular double-ended queue (deque).

Implement the MyCircularDeque class:

  • MyCircularDeque(int k) Initializes the deque with a maximum size of k.
  • boolean insertFront() Adds an item at the front of Deque. Returns true if the operation is successful, or false otherwise.
  • boolean insertLast() Adds an item at the rear of Deque. Returns true if the operation is successful, or false otherwise.
  • boolean deleteFront() Deletes an item from the front of Deque. Returns true if the operation is successful, or false otherwise.
  • boolean deleteLast() Deletes an item from the rear of Deque. Returns true if the operation is successful, or false otherwise.
  • int getFront() Returns the front item from the Deque. Returns -1 if the deque is empty.
  • int getRear() Returns the last item from Deque. Returns -1 if the deque is empty.
  • boolean isEmpty() Returns true if the deque is empty, or false otherwise.
  • boolean isFull() Returns true if the deque is full, or false otherwise.
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
class MyCircularDeque {
vector<int> A;
int st = 0, ed = 1;
public:
MyCircularDeque(int k) {
A = vector<int>(k + 2);
}

bool insertFront(int value) {
if(isFull()) return false;
A[st--] = value;
st = (st + A.size()) % A.size();
return true;
}

bool insertLast(int value) {
if(isFull()) return false;
if(isEmpty()) {
return insertFront(value);
}
A[ed++] = value;
ed %= A.size();
return true;
}

bool deleteFront() {
if(isEmpty()) return false;
st = (st + 1) % A.size();
return true;
}

bool deleteLast() {
if(isEmpty()) return false;

ed = (ed - 1 + A.size()) % A.size();
return true;

}

int getFront() {
if(isEmpty()) return -1;

return A[(st + 1) % A.size()];
}

int getRear() {
if(isEmpty()) return -1;

return A[(ed - 1 + A.size()) % A.size()];
}

bool isEmpty() {
return ed == (st + 1) % A.size();
}

bool isFull() {
return (ed + 1) % A.size() == st;
}
};

/**
* Your MyCircularDeque object will be instantiated and called as such:
* MyCircularDeque* obj = new MyCircularDeque(k);
* bool param_1 = obj->insertFront(value);
* bool param_2 = obj->insertLast(value);
* bool param_3 = obj->deleteFront();
* bool param_4 = obj->deleteLast();
* int param_5 = obj->getFront();
* int param_6 = obj->getRear();
* bool param_7 = obj->isEmpty();
* bool param_8 = obj->isFull();
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/18/PS/LeetCode/design-circular-deque/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.