力扣622.设计循环队列

力扣622.设计循环队列

    • 通过数组索引构建一个虚拟的首尾相连的环
    • 当front = rear时 队列为空
    • 当front = rear + 1时 队列为满 (最后一位不存)
cpp 复制代码
  class MyCircularQueue {
      int front;
      int rear;
      int capacity;
      vector<int> elements;
  public:
      MyCircularQueue(int k) {
          //最后一位不存元素 多开一个
          capacity = k+1;
          elements = vector<int>(capacity);
          rear = front = 0;
      }
      
      bool enQueue(int value) {
          if(isFull())
              return false;
          elements[rear] = value;
          rear = (rear + 1) % capacity;
          return true;
      }
      
      bool deQueue() {
          if(isEmpty())
              return false;
          front = (front + 1) % capacity;
          return true;
      }
      
      int Front() {
          if(isEmpty())
              return -1;
          return elements[front];
      }
      
      int Rear() {
          if(isEmpty())
              return -1;
          return elements[(rear - 1 + capacity) % capacity];
      }
      
      bool isEmpty() {
          return rear == front;
      }
      
      bool isFull() {
          return ((rear + 1) % capacity) == front;
      }
  };
相关推荐
阿豪学编程37 分钟前
LeetCode724.:寻找数组的中心下标
算法·leetcode
墨韵流芳1 小时前
CCF-CSP第41次认证第三题——进程通信
c++·人工智能·算法·机器学习·csp·ccf
csdn_aspnet2 小时前
C# 求n边凸多边形的对角线数量(Find number of diagonals in n sided convex polygon)
开发语言·算法·c#
禹中一只鱼2 小时前
【力扣热题100学习笔记】 - 哈希
java·学习·leetcode·哈希算法
凌波粒2 小时前
LeetCode--349.两个数组的交集(哈希表)
java·算法·leetcode·散列表
paeamecium3 小时前
【PAT甲级真题】- Student List for Course (25)
数据结构·c++·算法·list·pat考试
Book思议-3 小时前
【数据结构】栈与队列全方位对比 + C 语言完整实现
c语言·数据结构·算法··队列
SteveSenna3 小时前
项目:Trossen Arm MuJoCo
人工智能·学习·算法
NAGNIP3 小时前
一文搞懂CNN经典架构-DenseNet!
算法·面试
道法自然|~4 小时前
BugCTF黄道十二宫
算法·密码学