数据结构之【队列】

队列:先进先出,就是一块线性表,必须从头front的一方出队,从尾巴rear一方入队

我们生活中的队列就是这样的,出队的时候每次必须从a1出队,

         

当头出队后,尾巴就向前移动到下标为0处,这样的效率太低了,我们应该提高效率,每次头front出队了,就不需要向前移动

队头不需要每次都向前移动

如果front==rear的时候队为空,每次入队一个尾巴就向后面移动

假设在进队一个人尾巴就出去了,数组出了问题我们的 0 和1 还没有人,这样叫假溢出

由于rear可能比front大,也可能比front小,所以列队满的条件就是:(rear+1)%Queuesize==front;

队列长度的公式:(rear-front+Queuesize)%Queuesize

#include<iostream>
using namespace std;
#define MAXSIZE 10
class queue                   
{
public:
		queue(); 
		bool IsFull();
		bool IsEmpty();
		bool Enqueue(int);
		bool Dequeue(int&);
		
private:
		int front;
		int rear;
		int buf[MAXSIZE];
};
queue:queue()             构造函数
{
	this->rear=0;
	this->front=0;


}
bool queue:: IsFull()
{
	if((this->rear+1)%MAXSIZE==front)
			return true;
	else
			return false;
}
bool queue::IsEmpty()
{
	if(this->rear==this->front)
		return true;
	else
		return false;
}
bool queue::Enqueue(int d)
{
	if(IsFull())
		return false;
	this->buf[this->rear]=d;
	this->rear=(this->rear+1)%MAXSIZE;

}
bool queue::Dequeue(int& d)
{
	if(IsEmpty())
		reutrn false;
	d=buf[this->front];
	this->front=(this->front++)%MAXSIZE;     出队列 的头移动
}
int main()
{
	queue q;   实例化对象
	


}

猜你喜欢

转载自blog.csdn.net/weixin_40989362/article/details/81541508