首页 > 编程语言 >C++ 循环队列(基于数组)

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

时间:2022-10-12 17:35:02浏览次数:52  
标签:return 队列 C++ int isEmpty 数组 front els rear

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];
    }
};

 

标签:return,队列,C++,int,isEmpty,数组,front,els,rear
From: https://www.cnblogs.com/fanqshun/p/16785317.html

相关文章

  • 将1个数组拆分成多个数组
    代码:array(1个数组)size(按每多少个元素进行拆分)functionsplitArray(array,size){letdata=[];for(leti=0;i<array.length;i+=size){data.push(......
  • RabbitMQ 镜像队列
    一、基本原理1.工作原理搭建RabbitMQ集群以后,尽管交换器和绑定关系能够在单点故障问题上幸免于难,但是队列及其存储的消息却不行,这是因为队列进程及其内容仅仅维持......
  • C++ 实现视频文件播放(Windows Media Player、MFC、C#)
    <fontcolor=purplesize=5face="隶书">无为也,则用天下而有余;有为也,则为天下用而不足。1、简介https://docs.microsoft.com/en-us/windows/win32/wmp/about-the-windows-......
  • 二维数组面对对象array
    publicclassDemo05{publicstaticvoidmain(String[]args){/*[5][2]面对对象1,2array[0]2,3array[1]3,4array[2]......
  • 数组升序和数组填充array
    importjava.util.Arrays;publicclassDemo06{publicstaticvoidmain(String[]args){int[]a={1,2,5555,674,22};//System.out.println(a);......
  • 稀疏数组array
    publicclassDemo08{publicstaticvoidmain(String[]args){//创建一个二维数组5*5int[][]array1=newint[5][5];array1[1][2]=1;......
  • 数组长度,和,最大元素array
    publicclassDemo03{publicstaticvoidmain(String[]args){int[]arrays={1,2,3,4,5,6};//打印全部的数组长度for(inti=0;i<ar......
  • 反转数组array
    publicclassDemo04{publicstaticvoidmain(String[]args){int[]arrays={1,2,3,4,5,6};/*JDK1.5:没有下标for(intarray:arr......
  • c++读写文件
    #include<iostream>#include<fstream>#include<string>usingnamespacestd;intmain(){ofstreamf; f.open("test.txt",ios::out); f<<"aaaaaa"<<endl; ifst......
  • 单调栈与单调队列复习笔记
    简介有时候,我们让栈/队列中的所有元素满足单调,然后处理会比较方便。P2947[USACO09MAR]LookUpS给出一个长度为\(N\)的序列\(A\),求出一个序列\(P\),使得\(P_i\)......