环形队列

介绍

    环形队列是队列的一种特殊情况,也是基于队列的实现,队列是动态的集合,而环形队列则是固定长度的,当队列满时,则从队首删除元素。其原理基本和队列一致,都是实现先进先出的策略。

实现

    先定义数据,并且初始化:

static int* g_circularQueue = nullptr;
static int g_maxLength = 0;
static int g_length = 0;
static int g_head = 0;
static int g_tail = 0;

void init(int initLength)
{
	g_circularQueue = new int [initLength];
	g_maxLength = initLength;
	g_length = 0;
	g_head = 0;
	g_tail = 0;
}

    接着,先定义判断环形队列是否满,或者空:

bool isFull()
{
	return g_maxLength == g_length;
}

bool empty()
{
	return 0 == g_length;
}

    然后,就是入队:

void enqueue(int element)
{
	if (isFull())
	{
		dequeue();
	}
	g_circularQueue[g_tail] = element;
	++ g_length;

	g_tail = (g_tail + 1 ) % g_maxLength;
}

    入队之前,先判断是否满,如果满了,就先出队删除一个元素,再入队,入队之后,增加环形队列当前的长度,并且增加尾标志的值。这里用到%模符号,是因为g_tail不能大于g_maxLength。

    下面就是出队:

int dequeue()
{
	assert(0 != g_length);
	int element = g_circularQueue[g_head];
	g_head = (g_head + 1) % g_maxLength;
	-- g_length;
	return element;
}

    出队的时候减去当前长度,并且增加头的值。和尾一样,最大不能超过g_maxLength,所以用模%。

    最后,用来释放内存:

void finit()
{
	assert(nullptr != g_circularQueue);
	delete [] g_circularQueue;
}

    测试比较简单,就是输出头和尾的值,以及环形队列的长度:

int _tmain(int argc, _TCHAR* argv[])
{
	init(4);
	enqueue(1);
	cout << "enqueue head = " << g_head << ", tail = " << g_tail <<", length = " << g_length << endl;
	enqueue(2);
	cout << "enqueue head = " << g_head << ", tail = " << g_tail <<", length = " << g_length << endl;
	enqueue(3);
	cout << "enqueue head = " << g_head << ", tail = " << g_tail <<", length = " << g_length << endl;
	enqueue(4);
	cout << "enqueue head = " << g_head << ", tail = " << g_tail <<", length = " << g_length << endl;
	enqueue(5);
	cout << "enqueue head = " << g_head << ", tail = " << g_tail <<", length = " << g_length << endl;
	dequeue();
	cout << "dequeue head = " << g_head << ", tail = " << g_tail <<", length = " << g_length << endl;
	dequeue();
	cout << "dequeue head = " << g_head << ", tail = " << g_tail <<", length = " << g_length << endl;
	enqueue(1);
	cout << "enqueue head = " << g_head << ", tail = " << g_tail <<", length = " << g_length << endl;
	enqueue(2);
	cout << "enqueue head = " << g_head << ", tail = " << g_tail <<", length = " << g_length << endl;
	enqueue(3);
	cout << "enqueue head = " << g_head << ", tail = " << g_tail <<", length = " << g_length << endl;
	finit();
	return 0;
}

    输出:circularQueue-result

circularQueue-result

总结

    其实环形队列和队列是比较相似的,只是在队列的基础上把长度固定了。如果想要自动增长,则直接就可以用队列了,因为它的实现就是自动增加的,代码可以参考:队列

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Z小偉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值