数组实现循环队列

在用数组实现时,有以下几个地方需要注意:

1、队列的长度就是数组的长度

2、没有成员时,队头队尾都指向第一个位置,即下标为0

3、队头始终指向队列中最先进队的成员队尾始终指向队列中最后进队的成员的后面下一个位置

3、当队头与队尾的下标相同时,队列为空,因此队尾在指向第四个位置即下标为3时,就应该算队满,否则当队头下标为0时,最后一个位置即第五个位置也有成员,此时队尾下标为0,按照上面的思想应该算队列为空,与实际不符。因此队列的实际容量始终为数组容量减一。

4、按照上面的思想,队头和队尾下标表示应该为(当前下标+1)%数组容量,在第一圈为0,1,2,3,4,第二圈时继续自加明显不合适,因为下标因该为0,因此在自加后对数组容量取余

在这里插入图片描述

#include<iostream>
using namespace std;
#define MAXSIZE 10
class queue
{
public:
        queue();
        bool IsFull();
        bool IsEmpty();
        bool EnQueue(int);
        bool DeQueue(int&);
private:
        int buf[MAXSIZE];
        int rear;
        int front;
};
queue::queue()
{
        this->rear=0;
        this->front=0;
}
bool queue::IsEmpty()
{
        if(this->rear==this->front)
                return true;
        else
                return false;
}
bool queue::IsFull()
{
        if((this->rear+1)%MAXSIZE==this->front)
                return true;
        else
                return false;
}
bool queue::EnQueue(int data)
{
        if(IsFull())
                return false;
        this->buf[this->rear]=data;
        this->rear=(this->rear+1)%MAXSIZE;
        return true;
}
bool queue::DeQueue(int& data)
{
        if(IsEmpty())
                return false;
        data=this->buf[this->front];
        this->front=(this->front+1)%MAXSIZE;
}
int main()
{
        queue q;
        int i=0;
        while(i<20)
        {
                if(q.EnQueue(i))
                        cout<<"success "<<i<<endl;
                else
                        cout<<"fail "<<i<<endl;
                i++;
        }
        while(q.DeQueue(i))
                cout<<i<<" ";
        cout<<endl;
        return 0;
}

代码参考:https://blog.csdn.net/yangwenxiao123456/article/details/81639001

次要参考:https://www.cnblogs.com/han200113/p/11526956.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

触不可及<>

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值