循环队列-c++

 队列是一种常用的数据结构,但我们平常实现的队列有一个缺陷。想象一下,假设一个已经填满的队列,我们开始不断弹出队头元素,这时候我们会发现,虽然队尾看上去是满了,但实际上前面许多空间并没有使用,造成极大浪费。那么我们该怎么解决这个问题呢?

我们可以采用循环队列的方式。既然前面还没用,我们再绕回到前面不就好了吗。

具体看下图

 如果能理解这一点,那么下面的代码也就很显然了。

#include<iostream>
#include<cassert>
using namespace std;

#define CAPACITY 5

template<class T>
class LoopQueue
{
private:
	T* data;
	int front;//头
	int tail;//尾
	int capacity;

	void resize(int newcapacity)
	{
		T* newdata = new T[newcapacity];
		for (int i = 0; i < get_size(); i++)
		{
			newdata[i] = data[(i + front) % capacity];
		}
		data = newdata;
		front = 0;
		tail = get_size();
		data = newdata;
		newdata = nullptr;
	}

public:
	LoopQueue()
	{
		data = new T[CAPACITY];
		front = 0;
		tail = 0;
		capacity = CAPACITY;
	}

	LoopQueue(int cab)
	{
		data = new T[cab];
		front = 0;
		tail = 0;
		capacity = cab;
	}

	~LoopQueue()
	{
		delete[]data;
		data = nullptr;
	}

	bool isempty()
	{
		return front == tail;
	}

	int get_size()
	{
		return (tail + capacity - front) % capacity;
	}

	void enque(T elem)
	{
		if ((tail + 1) % capacity == front)
		{
			resize(2 * capacity);
		}

		data[tail++] = elem;
		tail = (tail + 1) % capacity;
	}

	T deque()
	{
		assert(front != tail);
		T res = data[front];
		front = (front + 1) % capacity;

		if (get_size() == capacity / 4 && capacity / 2) resize(capacity / 2);

		return res;
	}

	T get_front()
	{
		assert(front != tail);
		return data[front];
	}

};

应姐妹推荐,拿出全球高考秦究和游惑海报镇楼。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值