固定数组实现队列

设插入数据的位置是end,取出数据的位置是start
实现队列的时候,数组的循环使用。
在实现队列的时候,我们不应该考虑让end和start相互耦合到一块,这样会导致问题更加复杂,比如他们的起始位置,以及怎么判断队列是空OR队列是满?
解决方案:我们添加一个变量用来指示当前栈中元素的个数(length),通过该变量解耦start和end。再编写代码就比较简单了。。

#include <iostream>
#include <exception>

using namespace std;

class ArrayQueue
{
public:
	ArrayQueue(int initSize)
	{
		arr = new int[initSize];
		length = initSize;
		size = 0;
		first = 0;
		last = 0;
	}
	int peek()
	{
		if (size == 0)
		{
			throw new exception("the queue is empty");
		}
		return arr[first];
	}

	void push(int obj)
	{
		if (size == length)
		{
			throw new exception("the queue is full");
		}
		else
		{
			size++;
			arr[last] = obj;
			last = last == length - 1 ? 0:last + 1;
		}
	}
	int poll()
	{
		if (size == 0)
		{
			throw new exception("the queue is empty");
		}
		size--;
		int tmp = first;
		first = first == length ? 0 : first + 1;
		return arr[tmp];
	}
private:
	int *arr;
	int size;
	int first;
	int last;
	int length;
};


int main(int argc, char ** argv)
{
	ArrayQueue arrayqueue(20);
	arrayqueue.push(1);
	arrayqueue.push(2);
	arrayqueue.push(3);
	arrayqueue.push(4);
	printf("%d\t", arrayqueue.poll());
	printf("%d\t", arrayqueue.poll());
	printf("%d\t", arrayqueue.poll());
	printf("%d\t", arrayqueue.poll());

	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值