队列的顺序存储结构称为顺序队列,顺序队列实际上是运算受限的顺序表。与顺序栈类似,在队列的顺序存储结构中,用一组地址连续的存储单元一次存放从队列头到队列尾的元素。指针front和rear被分别用来队列头和队列尾元素的位置。在这里,我们设定初始化空队列时,front=rear=0;有新元素插入队列时,rear=rear+1;从队列中删除头元素时,front=front+1;当队列非空时,头指针指向头元素,而尾指针始终指向队尾元素的下一个位置。
queueArray.h
#include
using namespace std;
class QueueArray
{
public:
QueueArray(int MaxQueueSize = 10);
~QueueArray();
bool IsEmpty() const { return front==rear;};
bool IsFull() const { return (((rear+1)%MaxSize == front)? 1:0);};
void First(int& x) const; //返回队首元素
void Last(int& x) const; //返回队尾元素
bool Insert(const int& x); //插入元素
bool Delete(int& x); //删除元素
void Output();
private:
int front; //指向第一个元素
int rear; //指向队尾元素的下一个位置
int MaxSize; //队列数组的大小
int *queue; //数组
};
queueArray.cpp
#include "queueArray.h"
QueueArray::QueueArray(int MaxQueueSize)
{
MaxSize = MaxQueueSize+1;
queue = new int[MaxSize];
front = rear = 0;
}
QueueArray::~QueueArray()
{
if(queue)
delete queue;
}
void QueueArray::First(int& x) const
{
if(IsEmpty())
{
cout<<"队列为空!"<
return;
}
x = queue[front%MaxSize];
}
void QueueArray::Last(int& x) const
{
if(IsEmpty())
{
cout<<"队列为空!"<
return;
}
x = queue[rear-1];
}
bool QueueArray::Insert(const int &x)
{
if(IsFull())
{
cout<<"队列满!"<
return false;
}
queue[rear] = x;
rear = (rear+1)%MaxSize;
return true;
}
bool QueueArray::Delete(int &x)
{//删除第一个元素,并将其送入x
if(IsEmpty())
{
cout<<"队列为空!"<
return false;
}
x = queue[front];
front = (front+1)%MaxSize;
return true;
}
void QueueArray::Output()
{
for(int i=front; icout< << " ";
cout<}
测试文件:test.app
#include
#include "queueArray.h"
using namespace std;
int main()
{
int x = 0;
QueueArray *queueArray = new QueueArray(10);
for(int i=0; i<15; i++)
queueArray->Insert(i);
cout<<"当前队列中元素为:"<
queueArray->Output();
queueArray->First(x);
cout<<"队列顶部元素:"<
<
queueArray->Last(x);
cout<<"队列尾部元素:"<
<
queueArray->Insert(10);
cout<<"插入元素后,当前队列中元素如下:"<
queueArray->Output();
queueArray->Delete(x);
cout<<"删除元素"< << "后,当前队列中元素为:"<
queueArray->Output();
return 0;
}
结果如下: