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



  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值