队列的顺序存储结构

队列的顺序存储结构称为顺序队列,顺序队列实际上是运算受限的顺序表。与顺序栈类似,在队列的顺序存储结构中,用一组地址连续的存储单元一次存放从队列头到队列尾的元素。指针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; i
  
  

  
   
   
        cout<
    
    
     
     <<
     
     "  ";
    
    
    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;
}

结果如下: 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值