力扣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;
      }
  };
相关推荐
wow_DG12 分钟前
【C++✨】多种 C++ 解法固定宽度右对齐输出(每个数占 8 列)
开发语言·c++·算法
Epiphany.55622 分钟前
c++最长上升子序列长度
c++·算法·图论
Cx330❀1 小时前
【数据结构初阶】--排序(四):归并排序
c语言·开发语言·数据结构·算法·排序算法
余_弦1 小时前
区块链中的密码学 —— 密钥派生算法
算法·区块链
亲爱的非洲野猪2 小时前
令牌桶(Token Bucket)和漏桶(Leaky Bucket)细节对比
网络·算法·限流·服务
NAGNIP2 小时前
一文读懂LLAMA
算法
烧冻鸡翅QAQ2 小时前
62.不同路径
算法·动态规划
番薯大佬2 小时前
编程算法实例-冒泡排序
数据结构·算法·排序算法
queenlll2 小时前
P2404 自然数的拆分问题(典型的dfs)
算法·深度优先
wydaicls2 小时前
用函数实现方程函数解题
人工智能·算法·机器学习