程序员社区

循环队列

在这里插入图片描述
在这里插入图片描述
法1:用到的是我之前写的循环队列文章里面的方法
在这里插入图片描述
循环队列详解

#include<iostream>
using namespace std;
class MyCircularQueue {
private:
    int queue[1000];
    int head;
    int tail;
    int size;
public:
    MyCircularQueue(int k) 
    {
        size = k+1;
        head = tail = 0;
    }
    bool enQueue(int value) 
    {
        //先判断队列是否已经满了
        if ((tail + 1) % size == head)
        {
            return false;
        }
        //head指向的元素空间是浪费的
        queue[++tail] = value;
        return true;
    }

    bool deQueue() 
    {
        //判断队列是否为空
        if (head == tail)
            return false;
        //这里注意:从head右边开始一直到tail,这段区间是已经插入的元素
        head++;
        return true;
    }

    int Front() 
    {
        if (isEmpty())
            return -1;
        return queue[head + 1];
    }

    int Rear() {
        if (isEmpty())
            return -1;
        return queue[tail];
    }

    bool isEmpty() {
        if (head == tail)
            return true;
        return false;
    }

    bool isFull() {
        if ((tail + 1) % size == head)
            return true;
        return false;
    }
};

void test()
{
    MyCircularQueue* circularQueue = new MyCircularQueue(3); // 设置长度为 3
    cout<<circularQueue->enQueue(1)<<endl; //返回 true
    cout << circularQueue->enQueue(2) << endl; //返回 true
   cout<< circularQueue->enQueue(3)<<endl;// 返回 true
   cout<< circularQueue->enQueue(4)<<endl;// 返回 false,队列已满
    cout<<circularQueue->Rear()<<endl;// 返回 3
   cout<< circularQueue->isFull()<<endl;// 返回 true
    cout<<circularQueue->deQueue()<<endl;// 返回 true
    cout<<circularQueue->enQueue(4)<<endl;// 返回 true
    cout<<circularQueue->Rear()<<endl;// 返回 4
}
int main()
{
    test();
    return 0;
}

在这里插入图片描述

法2:这种方法较容易理解,实现起来简单,这里不做演示

在这里插入图片描述

赞(0) 打赏
未经允许不得转载:IDEA激活码 » 循环队列

相关推荐

  • 暂无文章

一个分享Java & Python知识的社区