数组实现循环队列

队列可用链表来实现,实现也很简单。但是队列也可用数组来实现,使用循环数组比链表有更高的效率。

由于循环数组的特殊性,一个循环数组中必须空出一个位置,不然无法判断队列是否为空或者为满的。

循环数组来实现队列的难点便在索引的值,我们要把数组当做一个圆来看,当索引来到数组的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();
    }
}

下面是测试结果图:
测试结果图

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值