队列可用链表来实现,实现也很简单。但是队列也可用数组来实现,使用循环数组比链表有更高的效率。
由于循环数组的特殊性,一个循环数组中必须空出一个位置,不然无法判断队列是否为空或者为满的。
循环数组来实现队列的难点便在索引的值,我们要把数组当做一个圆来看,当索引来到数组的0或者最后一个位置时,必须能够得到正确的索引。
下面是类声明,这只是简化版的:
class Queue
{
public:
Queue(int n=10);
~Queue();
void insert(int);
int top();
void pop();
bool empty();
private:
int *array;
int size; //the size of array
int length; //the really length of array
int head; //the head of Queue
int end; //the end of Queue
};
这里只给insert函数,top函数和pop函数的源代码:
void Queue::insert(int n)
{
if((end+1)%size == head )
{
cout<<"The queue is full \n";
return;
}
array[end]=n;
end=(end+1)%size; //找到正确的下个索引
}
int Queue::top()
{
return array[head];
}
void Queue::pop()
{
if(head==end)
{
cout<<"The Queue is empty \n";
return;
}
head = (head+1)%size;
}
下面是试验代码:
int main()
{
Queue queue(2);
queue.insert(1);
queue.insert(2);
queue.insert(3);
while(!queue.empty())
{
cout<<queue.top()<<endl;
queue.pop();
}
}
下面是测试结果图: