习题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()