力扣641 设计双端队列

119 阅读1分钟
class MyCircularDeque {
public:
    int capcaity;
    int length;
    int head;
    int rear;
    vector<int>vec;
    MyCircularDeque(int k) :vec(k){
        capcaity=k;
        length=0;
        head=0;
        rear=0;
        }
    /** Adds an item at the front of Deque. Return true if the operation is successful. */
    bool insertFront(int value) {
        if(isFull()) return false;
        length++;
        head=head-1;
        if (head==-1) head=capcaity-1;
        vec[head]=value;
        return true;
    }
    /** Adds an item at the rear of Deque. Return true if the operation is successful. */
    bool insertLast(int value) {
            if((length+1)>capcaity)  return false;//队满返回false
        length++;//入队长度+1
        rear=rear%capcaity+1;
        vec[rear-1]=value;
return true;
    }
    /** Deletes an item from the front of Deque. Return true if the operation is successful. */
    bool deleteFront() {
      if(length==0) return false;
        length--;
        head=(head+1)%capcaity;
return true;
    }
    /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
    bool deleteLast() {
        if(isEmpty()) return false;
        if(rear==0) rear=capcaity;
        rear--;
        length--;
        return true;
    }
    /** Get the front item from the deque. */
    int getFront() {
if(isEmpty()) return -1;
return vec[head];
    }
    /** Get the last item from the deque. */
    int getRear() {
if(isEmpty()) return -1;
if(rear==0) rear=capcaity;
return vec[rear-1];
    }
    /** Checks whether the circular deque is empty or not. */
    bool isEmpty() {
if(length==0) return true;
return false;
    }
    /** Checks whether the circular deque is full or not. */
    bool isFull() {
if(length==capcaity) return true;
else return false;
    }
};