实现一个循环队列
队列的特点就是先进先出,尾插头出。
涉及到循环,,,无论是数组还是链表,重点在于取余!!!,防止溢出。。。
例如数组大小为5,当队尾为4时,( 且 队头!= 队尾 ),再入队后,队尾应改变为0,需用取余。
#include
using namespace std;
class Queue {
public:
//构造函数
Queue(int size = 10) {
_que = new int[size];
_Front = _Tial = 0;
_size = size;
}
//析构函数
~Queue(){
delete[]_que;
_que = nullptr;
}
//拷贝构造
Queue (const Queue & que){
_que = new int[que._size];
for (int i = que._Front; i != que._Tial; i = (i + 1) % que._size) {
_que[i] = que._que[i];
}
_Front = que._Front;
_Tial = que._Tial;
_size = que._size;
}
//赋值拷贝构造
Queue & operator = (const Queue & que){
if (this == &que)
return *this;
delete[] _que;
_que = new int[que._size];
for (int i = que._Front; i != que._Tial; i = (i + 1) % que._size) {
_que[i] = que._que[i];
}
_Front = que._Front;
_Tial = que._Tial;
_size = que._size;
}
//入队
void push(int val){
if (full())
resize();
_que[_Tial] = val;
_Tial = (_Tial + 1) % _size;
}
//出队
void pop(){
if (empty())
return;
_Front = (_Front + 1) % _size;
}
//获得队头数据
int front(){
return _que[_Front];
}
//判满
bool full() { return _Front == (_Tial+1)%_size; }
//判空
bool empty() { return _Front == _Tial; }
//扩容
void resize() {
int * _queue = new int[_size*2];
int j = 0;
for (int i = _Front; i != _Tial; i = (i + 1) % _size) {
_queue[j++] = _que[i];
}
delete[]_que;
_que = _queue;
_Front = 0;
_Tial = _size;
_size *= 2;
}
private:
int* _que; //申请的空间
int _Front; //队头
int _Tial; //队尾
int _size; //空间大小
};
int main() {
Queue q;
Queue q2;
q.push(10);
q.push(20);
q.pop();
Queue q1 = q;
q2 = q1;
cout << q2.front() << endl;
}