C++ 循环队列(基于数组)

Code: 

class CircularQueue {
  private: 
    // 容量
    int C;
    // 容器
    vector<int> els;
    // 队头指针
    int front;
    // 队尾指针
    int rear;

  public:
    /* 初始化队列 */ 
    CircularQueue(int k) {
      // 空间大小为 k+1
      C = k + 1;
      // 初始化容器
      els = vector<int>(C);
      // 队头指针索引初始为0
      front = 0;
      // 队尾指针索引初始为0
      rear = 0;
    }

    /**
     * 入队操作
     */
    bool enQueue(int val) {
      if (isFull()) {
        return false;
      }
      // 在队列的尾部插入一个元素
      els[rear] = val;
      // 同时将队尾索引rear更新为(rear + 1) % capacity
      rear = (rear + 1) % C;
      return true;
    }

    /**
     * 出队操作
     */
    bool deQueue() {
      if (isEmpty()) {
        return false;
      }
      // 将队首索引front更新为(front + 1) % capacity
      front = (front + 1) % C;
      return true;
    }

    /**
     * 是否队满 
     */
    bool isFull() {
      return (rear + 1) % C == front;
    }

    /**
     * 是否队空
     */
    bool isEmpty() {
      return front == rear;
    }

    /**
     * 获取队头元素 
     */
    int getFront() {
      if (isEmpty()) {
        return -1;
      }
      return els[front];
    }

    /**
     * 获取队尾元素 
     */
    int getRear() {
      if (isEmpty()) {
        return -1;
      }
      return els[(rear - 1 + C) % C];
    }
};

 

posted @ 2022-10-12 17:25  樊顺  阅读(57)  评论(0编辑  收藏  举报