641. Design Circular Deque

problem

solution

  • be careful of pointer out of range
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    class MyCircularDeque {
    private:
    vector<int> nums;
    int cap, front, back;
    public:
    MyCircularDeque(int k) {
    cap = k;
    front = back = 0;
    nums = vector<int> (k, -1);
    }

    bool insertFront(int value) {
    if(isFull()) return false;
    front = (front-1+cap)%cap;
    nums[front] = value;
    return true;

    }

    bool insertLast(int value) {
    if(isFull()) return false;
    nums[back] = value;
    back = (back+1)%cap;
    return true;

    }

    bool deleteFront() {
    if(isEmpty()) return false;
    nums[front] = -1;
    front = (front+1)%cap;
    return true;

    }

    bool deleteLast() {
    if(isEmpty()) return false;
    back = (back-1+cap)%cap;
    nums[back] = -1;
    return true;
    }

    int getFront() {
    if(isEmpty()) return -1;
    return nums[front];
    }

    int getRear() {
    if(isEmpty()) return -1;
    return nums[(back-1+cap)%cap];
    }

    bool isEmpty() {
    return nums[front]==-1 && (back==front);

    }

    bool isFull() {
    return nums[front]!=-1 && (back==front);
    }
    };