Skip to content

Commit cc47394

Browse files
authored
Create design-circular-deque.cpp
1 parent 930b3df commit cc47394

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

C++/design-circular-deque.cpp

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
// Time: O(1)
2+
// Space: O(k)
3+
4+
class MyCircularDeque {
5+
public:
6+
/** Initialize your data structure here. Set the size of the deque to be k. */
7+
MyCircularDeque(int k) :
8+
start_(0),
9+
size_(0),
10+
buffer_(k, 0) {
11+
12+
}
13+
14+
/** Adds an item at the front of Deque. Return true if the operation is successful. */
15+
bool insertFront(int value) {
16+
if (isFull()) {
17+
return false;
18+
}
19+
start_ = (start_ - 1 + buffer_.size()) % buffer_.size();
20+
buffer_[start_] = value;
21+
++size_;
22+
return true;
23+
}
24+
25+
/** Adds an item at the rear of Deque. Return true if the operation is successful. */
26+
bool insertLast(int value) {
27+
if (isFull()) {
28+
return false;
29+
}
30+
buffer_[(start_ + size_) % buffer_.size()] = value;
31+
++size_;
32+
return true;
33+
}
34+
35+
/** Deletes an item from the front of Deque. Return true if the operation is successful. */
36+
bool deleteFront() {
37+
if (isEmpty()) {
38+
return false;
39+
}
40+
start_ = (start_ + 1) % buffer_.size();
41+
--size_;
42+
return true;
43+
}
44+
45+
/** Deletes an item from the rear of Deque. Return true if the operation is successful. */
46+
bool deleteLast() {
47+
if (isEmpty()) {
48+
return false;
49+
}
50+
--size_;
51+
return true;
52+
}
53+
54+
/** Get the front item from the deque. */
55+
int getFront() {
56+
return isEmpty() ? -1 : buffer_[start_];
57+
}
58+
59+
/** Get the last item from the deque. */
60+
int getRear() {
61+
return isEmpty() ? -1 : buffer_[(start_ + size_ - 1) % buffer_.size()];
62+
}
63+
64+
/** Checks whether the circular deque is empty or not. */
65+
bool isEmpty() {
66+
return size_ == 0;
67+
}
68+
69+
/** Checks whether the circular deque is full or not. */
70+
bool isFull() {
71+
return size_ == buffer_.size();
72+
}
73+
74+
private:
75+
int start_;
76+
int size_;
77+
vector<int> buffer_;
78+
};
79+
80+
/**
81+
* Your MyCircularDeque object will be instantiated and called as such:
82+
* MyCircularDeque obj = new MyCircularDeque(k);
83+
* bool param_1 = obj.insertFront(value);
84+
* bool param_2 = obj.insertLast(value);
85+
* bool param_3 = obj.deleteFront();
86+
* bool param_4 = obj.deleteLast();
87+
* int param_5 = obj.getFront();
88+
* int param_6 = obj.getRear();
89+
* bool param_7 = obj.isEmpty();
90+
* bool param_8 = obj.isFull();
91+
*/
92+

0 commit comments

Comments
 (0)