3.C++实现简单的队列

习题3.编写一个类,实现简单的队列

3.编写一个类,实现简单的队列。队列中有以下操作:
> 元素入队 void push(int);
> 元素出队 void pop();
> 读取队头元素 int front();
> 读取队尾元素 int back();
> 判断队列是否为空 bool emty();
> 判断队列是否已满 bool full();

注意循环队列的使用

解题思路:

使用循环队列实现 :先进先出。

有头尾部,添加一个元素后,尾部向后移一位(尾部指向空,所以会少一个大小);删除一个元素,头部向后移一位

  • 循环队列需要*_data数组储存数据。
  • 需要队列的大小_size,循环队列能储存最大的数据为_size - 1
  • 有头尾部_front 、_rear,初始状态头尾指针在同一位置。
  • 队列为满需要满足(_rear + 1)%_size ==_front

数据成员:

队列的大小 int _size;

头部 int _front;

尾部 int _rear;

条件:

队列为空 _front == _rear

队列为满 (_rear + 1)%_size == _front

操作:

元素入队: _data[_rear++] == value

_rear %= _size (防止_rear在一圈的最后的位置)

元素出队: ++front (直接到下一个位置,不用管其数据,下次数据直接覆盖)

_front %= size (防止_front在一圈的最后位置)

获得队头元素: _data[_front];

获得队尾元素: _data[(_rear-1 + _size) % _size] (防止尾部在最开始,减一后成为负数了)

#include <iostream>

using std::cout;
using std::endl;

class Queue
{
public:
    //构造函数
    Queue(int sz = 10)
    : _size(sz)
    , _front(0)
    , _rear(0)
    , _data(new int[_size]())
    {
        cout << "Queue(int sz = 10)" <<endl;
    }

    //判断队列是否为空
    bool empty()
    {
        return (_front == _rear);
    }

    //判断队列是否满
    bool full()
    {
        return (_rear + 1) % _size == _front;
    }

    //获得队列头元素
    int getfront()
    {
        return _data[_front];
    }
    
    //获得队列尾元素
    int getback()
    {
        return _data[(_rear - 1 + _size) % _size];
    }

    //压入队列
    void push(const int &value)
    {
        if(!full())
        {
            _data[_rear++] = value;
            _rear %= _size;
        }
        else
        {
            cout << "Queue is full, cannot add any data!!" << endl;
        }
    }

    //弹出队列
    void pop()
    {
        if(!empty())
        {
            ++_front;
        }
        else
        {
            cout << "Queue is empty, cannot pop any data!!" << endl;
        }
    }

    //析构函数
    ~Queue()
    {
        cout << "~Queue()" << endl;
        if(_data)
        {
            delete []_data;
            _data = nullptr;
        }
    }
private:
    int _size;
    int _front;
    int _rear;
    int *_data;

};

int main()
{
    Queue que;
    que.push(1);
    for(int idx = 2; idx != 13; idx++)
    {
        que.push(idx);    
    }
    cout << "得到队列最后的一个元素:";
    cout << que.getback() << endl;
    
    cout << "队列的所有元素:";
    while(!que.empty())
    {
        cout << que.getfront() << " ";
        que.pop();
    }
    cout << endl;
    return 0;
}
结果:

Queue(int sz = 10)
Queue is full, cannot add any data!!
Queue is full, cannot add any data!!
Queue is full, cannot add any data!!
得到队列最后的一个元素:9
队列的所有元素:1 2 3 4 5 6 7 8 9 
~Queue()
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值