目录
队列的应用
队列的定义
队列的代码实现
队列类
#include<iostream>
using namespace std;
#define maxsize 1000
typedef int elemtype;
class Sqqueue {
public:
static Sqqueue* get()
{
static Sqqueue a;
return &a;
}
public:
void initstack();
void destroystack();
bool push(elemtype in);
bool pop(elemtype &a);
elemtype getsize();
private:
elemtype* base;//动态数组
int front;//队头
int rear;//队尾
int size;//队列长度
};
// front rear 表示数组下标 类似指针的作用
初始化队列
void Sqqueue::initstack()//初始化队列
{
this->base = new elemtype[maxsize];
if (this->base == NULL)
exit(0);
this->front = this->rear =this->size= 0;
}
销毁队列
void Sqqueue::destroystack()//删除队列
{
if (this->base) {
delete this->base;
this->front=this->rear = this->size=NULL;
this->base = NULL;
}
}
添加元素
bool Sqqueue::push(elemtype in) //压入元素
{
if (this->size!=maxsize)
{
this->base[this->rear] = in;
this->rear=(this->rear++)%maxsize;//循环队列
this->size++;
return 1;
}
return 0;
}
//这里的求模运算 是循环队列 队尾标记在超出数组之后会循环到数组头部这样就不会造成假溢出
弹出元素
bool Sqqueue::pop(elemtype &a)//弹出元素
{
if (this->size!=0)
{
a=this->base[this->front];
this->front = (this->front++) % maxsize;
this->size--;
return 1;
}
return 0;
}
//同上 打造循环队列