Skip to content

Commit 7b7be79

Browse files
authored
Create design-circular-queue.cpp
1 parent ce7ffc4 commit 7b7be79

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

C++/design-circular-queue.cpp

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// Time: O(1)
2+
// Space: O(k)
3+
4+
class MyCircularQueue {
5+
public:
6+
/** Initialize your data structure here. Set the size of the queue to be k. */
7+
MyCircularQueue(int k) :
8+
start_(0),
9+
size_(0),
10+
buffer_(k, 0) {
11+
12+
}
13+
14+
/** Insert an element into the circular queue. Return true if the operation is successful. */
15+
bool enQueue(int value) {
16+
if (isFull()) {
17+
return false;
18+
}
19+
buffer_[(start_ + size_) % buffer_.size()] = value;
20+
++size_;
21+
return true;
22+
}
23+
24+
/** Delete an element from the circular queue. Return true if the operation is successful. */
25+
bool deQueue() {
26+
if (isEmpty()) {
27+
return false;
28+
}
29+
start_ = (start_ + 1) % buffer_.size();
30+
--size_;
31+
return true;
32+
}
33+
34+
/** Get the front item from the queue. */
35+
int Front() {
36+
return isEmpty() ? -1 : buffer_[start_];
37+
}
38+
39+
/** Get the last item from the queue. */
40+
int Rear() {
41+
return isEmpty() ? -1 : buffer_[(start_ + size_ - 1) % buffer_.size()];
42+
}
43+
44+
/** Checks whether the circular queue is empty or not. */
45+
bool isEmpty() {
46+
return size_ == 0;
47+
}
48+
49+
/** Checks whether the circular queue is full or not. */
50+
bool isFull() {
51+
return size_ == buffer_.size();
52+
}
53+
54+
private:
55+
int start_;
56+
int size_;
57+
vector<int> buffer_;
58+
};
59+
60+
/**
61+
* Your MyCircularQueue object will be instantiated and called as such:
62+
* MyCircularQueue obj = new MyCircularQueue(k);
63+
* bool param_1 = obj.enQueue(value);
64+
* bool param_2 = obj.deQueue();
65+
* int param_3 = obj.Front();
66+
* int param_4 = obj.Rear();
67+
* bool param_5 = obj.isEmpty();
68+
* bool param_6 = obj.isFull();
69+
*/
70+

0 commit comments

Comments
 (0)