I'm posting a solution for LeetCode's "Design Circular Deque". If you'd like to review, please do so. Thank you!
Problem
Design your implementation of the circular double-ended queue (deque).
Your implementation should support following operations:
MyCircularDeque(k)
: Constructor, set the size of the deque to be k.insertFront()
: Adds an item at the front of Deque. Return true if the operation is successful.insertLast()
: Adds an item at the rear of Deque. Return true if the operation is successful.deleteFront()
: Deletes an item from the front of Deque. Return true if the operation is successful.deleteLast()
: Deletes an item from the rear of Deque. Return true if the operation is successful.getFront()
: Gets the front item from the Deque. If the deque is empty, return -1.getRear()
: Gets the last item from Deque. If the deque is empty, return -1.isEmpty()
: Checks whether Deque is empty or not.isFull()
: Checks whether Deque is full or not.
Example:
MyCircularDeque circularDeque = new MycircularDeque(3); // set the size to be 3 circularDeque.insertLast(1); // return true circularDeque.insertLast(2); // return true circularDeque.insertFront(3); // return true circularDeque.insertFront(4); // return false, the queue is full circularDeque.getRear(); // return 2 circularDeque.isFull(); // return true circularDeque.deleteLast(); // return true circularDeque.insertFront(4); // return true circularDeque.getFront(); // return 4
Note:
- All values will be in the range of [0, 1000].
- The number of operations will be in the range of [1, 1000].
- Please do not use the built-in Deque library.
Code:
// The following block might slightly improve the execution time; // Can be removed; static const auto __optimize__ = []() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return 0; }(); // Most of headers are already included; // Can be removed; #include <cstdint> #include <vector> struct MyCircularDeque { MyCircularDeque(int k): stream(k, 0), counts(0), k(k), head(k - 1), tail(0) {} const bool insertFront( const int value ) { if (isFull()) { return false; } stream[head] = value; --head; head += k; head %= k; ++counts; return true; } const bool insertLast(const int value) { if (isFull()) { return false; } stream[tail] = value; ++tail; tail %= k; ++counts; return true; } const bool deleteFront() { if (isEmpty()) { return false; } ++head; head %= k; --counts; return true; } const bool deleteLast() { if (isEmpty()) { return false; } --tail; tail += k; tail %= k; --counts; return true; } const int getFront() { return isEmpty() ? -1 : stream[(head + 1) % k]; } const int getRear() { return isEmpty() ? -1 : stream[(tail - 1 + k) % k]; } const bool isEmpty() { return !counts; } const bool isFull() { return counts == k; } private: using ValueType = std::uint_fast16_t; std::vector<ValueType> stream; ValueType counts; ValueType k; ValueType head; ValueType tail; };