赞
踩
//双向循环队列代码实现(C++) class MyCircularDeque { private: vector<int> arr; //head指向数组第一个数据,tail指向数组最后一个数据的下一个位置,count为数组元素个数 int head,tail,count; public: /** Initialize your data structure here. Set the size of the deque to be k. */ MyCircularDeque(int k):arr(k),head(0),tail(0),count(0) { } /** Adds an item at the front of Deque. Return true if the operation is successful. */ bool insertFront(int value) { if(isFull()) return false; head = head - 1; if(head == -1) head = arr.size()-1; arr[head] = value; count += 1; return true; } /** Adds an item at the rear of Deque. Return true if the operation is successful. */ bool insertLast(int value) { if(isFull()) return false; arr[tail] = value; tail = tail+1; if(tail == arr.size()) tail = 0; count += 1; return true; } /** Deletes an item from the front of Deque. Return true if the operation is successful. */ bool deleteFront() { if(isEmpty()) return false; head = (head+1)%arr.size(); count -= 1; return true; } /** Deletes an item from the rear of Deque. Return true if the operation is successful. */ bool deleteLast() { if(isEmpty()) return false; tail = (tail-1+arr.size())%arr.size(); count -= 1; return true; } /** Get the front item from the deque. */ int getFront() { if(isEmpty()) return -1; return arr[head]; } /** Get the last item from the deque. */ int getRear() { if(isEmpty()) return -1; return arr[(tail-1+arr.size())%arr.size()]; } /** Checks whether the circular deque is empty or not. */ bool isEmpty() { return count == 0; } /** Checks whether the circular deque is full or not. */ bool isFull() { return count == arr.size(); } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。