队列的基础概念及代码实现

 

目录

队列的应用 

队列的定义​编辑

队列的代码实现

队列类

初始化队列

销毁队列

添加元素

弹出元素


 

队列的应用 

 

 

 队列的定义

 

 队列的代码实现

 队列类

#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;
}

//同上 打造循环队列

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值