设插入数据的位置是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;
}