当前位置: 首页 > article >正文

c++环形队列

c++环形队列

  • c++环形队列

c++环形队列

#pragma once

#include <iostream>
#include <vector>

/// <summary>
/// - 环形队列
/// - 不是线程安全
/// </summary>
/// <typeparam name="T"></typeparam>
template <typename T>
class CircularQueue
{
	int rear, front;
	int size;
	T* arr = nullptr;

	int _len = 0;
public:
	CircularQueue(int s)
	{
		front = rear = -1;
		size = s;
		arr = new T[s];

		_len = 0;
	}

	~CircularQueue() {
		if (arr)
		{
			delete[]arr;
		}
	};

	bool enQueue(T value)
	{
		if ((front == 0 && rear == size - 1) ||
			((rear + 1) % size == front))
		{
			printf("\nQueue is Full");
			return false;
		}

		_len++;

		if (front == -1)
		{
			front = rear = 0;
			arr[rear] = value;
		}

		else if (rear == size - 1 && front != 0)
		{
			rear = 0;
			arr[rear] = value;
		}

		else
		{
			rear++;
			arr[rear] = value;
		}

		return true;
	};



	bool deQueue(T* val = nullptr) {

		if (front == -1)
		{
			printf("\nQueue is Empty");
			return false;
		}

		_len--;

		T data = arr[front];
		arr[front] = -1;
		if (front == rear)
		{
			front = -1;
			rear = -1;
		}
		else if (front == size - 1)
			front = 0;
		else
			front++;

		if (val)
		{
			*val = data;
		}
		

		return true;
	};

	void autoQueue(T value) {

		while (enQueue(value) == false)
		{
			deQueue();
		}
	};

	int len()
	{
		return _len;
	};

	std::vector<T> list()
	{
		std::vector<T> vals;

		if (front == -1)
		{
			return vals;
		}

		if (rear >= front)
		{
			for (int i = front; i <= rear; i++)
			{
				vals.push_back(arr[i]);
			}

		}
		else
		{
			for (int i = front; i < size; i++)
			{
				vals.push_back(arr[i]);
			}

			for (int i = 0; i <= rear; i++)
			{
				vals.push_back(arr[i]);
			}
		}

		return vals;
	}

	void displayQueue() {

		std::vector<T> ls = list();
		printf("\n displayQueue: ");
		for (size_t i = 0; i < ls.size(); i++)
		{
			printf("%d ", ls[i]);
		}
		printf("\n");
	};
};

//int main()
//{
//	CircularQueue<int> q(5);
//	q.autoQueue(14);
//	q.autoQueue(22);
//	q.autoQueue(13);
//	q.autoQueue(-6);
//
//	q.displayQueue();
//
//	q.autoQueue(9);
//	q.autoQueue(20);
//	q.autoQueue(5);
//
//	q.displayQueue();
//
//	q.autoQueue(20);
//
//	q.displayQueue();
//	return 0;
//}




http://www.kler.cn/news/149300.html

相关文章:

  • Linux grep命令
  • JavaWeb后端数据库MySQL的使用
  • 平凯星辰携手教育部教育管理信息中心,助力普惠教育数字化
  • Python与设计模式--桥梁模式
  • 互联网程序设计HTML+CSS+JS
  • Debian10安装VMware Tools
  • torch::和at:: factory function的差別
  • 【问题系列】消费者与MQ连接断开问题解决方案(一)
  • Go使用logrus框架
  • Unity 轨道展示系统(DollyMotion)
  • go标准库
  • 基于协同过滤算法的音乐推荐系统的研究与实现
  • 激光雷达毫米波雷达
  • PyTorch:模型加载方法详解
  • Vue2 若依框架头像上传 全部代码
  • 建筑工程模板包工包料价格
  • Kubernetes基础(九)-标签管理
  • 【Web】攻防世界 难度3 刷题记录(1)
  • Linux 调试工具:gdb
  • 使用shell快速查看电脑曾经连接过的WiFi密码
  • 记一次简单的PHP反序列化字符串溢出
  • 交流负载的功能实现原理
  • 各种排序算法
  • sed应用
  • 视觉CV-AIGC一周最新技术精选(2023-11)
  • 【面经八股】搜广推方向:面试记录(四)
  • git commit 撤销的三种方法
  • Kotlin学习——kt里的集合,Map的各种方法之String篇
  • QT6 Creator编译KDDockWidgets并部署到QT
  • C#通过NPOI 读、写Excel数据;合并单元格、简单样式修改;通过读取已有的Excel模板另存为文件