【力扣】探索队列:设计循环队列

题目链接

  1. 题目描述:
设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓
冲器”。

循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但
是使用循环队列,我们能使用这些空间去存储新的值。

你的实现应该支持如下操作:

MyCircularQueue(k): 构造器,设置队列长度为 k 。
Front: 从队首获取元素。如果队列为空,返回 -1 。
Rear: 获取队尾元素。如果队列为空,返回 -1enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。
deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。
isEmpty(): 检查循环队列是否为空。
isFull(): 检查循环队列是否已满。
  1. C++实现MyCircularQueue类:
class MyCircularQueue {
    private:
    int* arr_int;
    int ihead;//队头指针
    int itail;//队尾指针
    int size;//有效成员
    int cap;//容量
public:
    /** Initialize your data structure here. Set the size of the queue to be k. */
    MyCircularQueue(int k) {
        arr_int=new int[k];
        size=0;
        ihead=0;
        itail=0;
        cap=k;
            }
    
    /** Insert an element into the circular queue. Return true if the operation is successful. */
    bool enQueue(int value) {
        //itail++判断is_full是否>=size
        //如果ture则返回
        if(isFull())
            return false;
        //false情况插入数据
        else {
            //先判断循环队列是否为空:为空当前格插入;不为空下一格插入
            if(!isEmpty())itail++;
            //判断要插入的格是否超过固定数组下标尾部:超过调整下标至固定数组内
            if(itail>=cap)itail=itail-cap;
            //插入数据
            arr_int[itail]=value;
            size++;
            return true;
        }
    }
    
    //{0}
    //itail=0
    //ihead=1
    //size=0
    
    /** Delete an element from the circular queue. Return true if the operation is successful. */
    bool deQueue() {
        if(isEmpty())
            return false;
        else
        {
            //删除当前格的数据
            arr_int[ihead]=0;
            size--;
            //判断循环队列是否为空:为空ihead不变;不为空ihead++
            if(!isEmpty())ihead++;
            //判断队头是否超过固定数组下标尾部:超过调整下标至固定数组内
             if(ihead>=cap)ihead=ihead-cap;
            
            return true;
        }
    }
    
    /** Get the front item from the queue. */
    int Front() {
        if(size<=0)return -1;
        else
        {
            return arr_int[ihead];
        }
    }
    
    /** Get the last item from the queue. */
    int Rear() {
        if(size<=0)return -1;
        else
        {
            return arr_int[itail];
        }
    }
    
    /** Checks whether the circular queue is empty or not. */
    bool isEmpty() {
        if(size>0)return false;
        else return true;
    }
    
    /** Checks whether the circular queue is full or not. */
    bool isFull() {
      if(size<cap)return false;
        else return true;
    }
    ~MyCircularQueue()
    {
        delete[] arr_int;
    }
};
  1. 题目分析:
  • 该题目需要实现环形队列MyCircularQueue类中元素的增删以及判断队列是否为空及为队列为满:以固定大小的数组结构int[k]
    (MyCircularQueue对象构造时传入k值)存储环形队列的元素,增加元素时队尾指针加一(判断队尾指针是否超过数组大小即越界)
    ,删除元素时队头指针加一(判断队头指针是否超过数组大小)。

  • 注意循环队列为空时:添加元素时队尾指针不需要加一;删除元素时队头指针不需要加一。

发布了25 篇原创文章 · 获赞 4 · 访问量 2550

猜你喜欢

转载自blog.csdn.net/qq_43167575/article/details/104132914