当前位置:   article > 正文

双向循环队列代码实现(C++)_基于两端操作的循环队列的实现 c++

基于两端操作的循环队列的实现 c++
//双向循环队列代码实现(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();
    }
};


  • 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
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/412773
推荐阅读
相关标签
  

闽ICP备14008679号