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