This is a good design question. It seems boring, but actually can test some data structure capability.
This question is similar to another question: Leetcode 641 Design Circular Deque.
See the code below:
class MyCircularQueue { private: vector<int> buffer; int front; int rear; int len; int ct; public: /** Initialize your data structure here. Set the size of the queue to be k. */ MyCircularQueue(int k): buffer(k, 0), front(0), rear(0), len(k), ct(0) { } /** Insert an element into the circular queue. Return true if the operation is successful. */ bool enQueue(int value) { if(isFull()) return false; buffer[rear] = value; rear = (rear + 1)%len; ++ct; return true; } /** Delete an element from the circular queue. Return true if the operation is successful. */ bool deQueue() { if(isEmpty()) return false; front = (front + 1)%len; --ct; return true; } /** Get the front item from the queue. */ int Front() { if(isEmpty()) return -1; return buffer[front]; } /** Get the last item from the queue. */ int Rear() { if(isEmpty()) return -1; return buffer[(rear - 1 + len)%len]; } /** Checks whether the circular queue is empty or not. */ bool isEmpty() { return ct == 0; } /** Checks whether the circular queue is full or not. */ bool isFull() { return ct == len; } }; /** * Your MyCircularQueue object will be instantiated and called as such: * MyCircularQueue* obj = new MyCircularQueue(k); * bool param_1 = obj->enQueue(value); * bool param_2 = obj->deQueue(); * int param_3 = obj->Front(); * int param_4 = obj->Rear(); * bool param_5 = obj->isEmpty(); * bool param_6 = obj->isFull(); */
No comments:
Post a Comment