重学数据结构系列之——队列

学习来源:计蒜客

队列

1.定义


你就想象一下现实中的排队,但要理想化,不能插队哦
所以队列有一个很重要的性质,就是先进先出,First In First Out(FIFO)。

2.队列的实现

#include <iostream>
#include <cassert>

using namespace std;

class Queue{
private:
	//保存队列的具体数据的
	int* data;
	//头 尾 队列长度
	int head, tail, length;
public:
	//构造函数 length_input:初始队列长度
	Queue(int length_input){
		data = new int[length_input];
		length = length_input;
		//一开始队列为空,头为0,尾设置为-1
		//只有一个元素时,头尾都是它,head=tail=0
		head = 0;
		tail = -1;
	}
	//析构函数
	~Queue(){
		delete[] data;
	}
	//加入队列
	void push(int element){
		//队列不能满了,因为tail一般是从0到length-1,空队列就-1
		//若tail + 1 == length,说明队列的尾是第length个元素了,已经没位置了
		if (tail + 1 < length) {
			//尾部移动,将元素放到相应位置
			tail++;
			data[tail] = element;
		}
	}
	//队列元素的输出
	void output(){
		//从头遍历到尾输出
		for (int i = head; i <= tail; i++) {
			cout<<data[i]<<" ";
		}
		cout<<endl;
	}
	//返回队首元素
	int front(){
		//判断队列不为空,为空则退出
		//这是宏断言,条件为true,继续执行,否则退出程序
		assert(head <= tail);
		return data[head];
	}
	
	//删除队首元素
	void pop(){
		assert(head <= tail);
		//head往后移动一位就表示删除队首元素
		head++;
	}

};

int main(){
	Queue queue(100);
	for (int i = 1; i <= 10; i++) {
		queue.push(i);
	}
	queue.output();
	cout<<queue.front()<<endl;
	queue.pop();
	queue.output();
	return 0;
}

3.运行结果



2.循环队列


1.引入


如果一个队列在不断的执行插入、弹出、插入、弹出……那么可以想象,当执行到head== tail==length-1 ,便不能再插入到队列中了,而此时队列其实是空的。
对于这种存储区没有用满,而队列却发生了溢出的现象,我们称之为“假上溢”,也叫“假溢出”。我们就可以使用循环队列解决了。

2.实现

#include <iostream>
#include <cassert>

using namespace std;

class Queue{
private:
	//保存队列的具体数据的
	int* data;
	//头 尾 队列长度 队列中元素的格式
	int head, tail, length, count;
public:
	//构造函数 length_input:初始队列长度
	Queue(int length_input){
		data = new int[length_input];
		length = length_input;
		//一开始队列为空,头为0,尾设置为-1
		//只有一个元素时,头尾都是它,head=tail=0
		head = 0;
		tail = -1;
		count = 0;
	}
	//析构函数
	~Queue(){
		delete[] data;
	}
	//加入队列
	void push(int element){
		//元素总数小于总长才可插入	
		if (count < length) {
			//这里的尾+1后要对总长取模
		    tail = (tail + 1) % length;
            data[tail] = element;
			//计数的也要+1
            count++;
        }
	}
	//队列元素的输出
	void output(){
		//从头遍历到尾输出
		for (int i = head; i != tail+1; i = (i+1)%length) {
			cout<<data[i]<<" ";
		}
		cout<<endl;
	}
	//返回队首元素
	int front(){
		//判断队列不为空,为空则退出,这里用count来判断,方便多了
		//这是宏断言,条件为true,继续执行,否则退出程序
		assert(count > 0);
		return data[head];
	}
	
	//删除队首元素
	void pop(){
		assert(count > 0);
		//head往后移动一位就表示删除队首元素
		head = (head + 1) % length;
		count--;
	}

};


int main(){
	Queue queue(11);
	for (int i = 1; i <= 10; i++) {
		queue.push(i);
	}
	queue.output();
	//cout<<queue.front()<<endl;
	queue.pop();
	queue.pop();
	queue.output();
	queue.push(11);
	queue.push(12);
	queue.output();
	return 0;
}

3.运行结果



原文地址:https://www.cnblogs.com/cnsec/p/13286561.html