C++数组实现队列

C++数组实现队列

队列是一种先进先出的数据结构,队列元素从队头出队,从队尾入队,如一组数入队顺序为:5 4 3 2 1,则出队顺序也为:5 4 3 2 1。

这里使用静态数组实现一个简易队列,该实现主要通过三个标识符标记队列元素

    int m_length; //队列实际元素个数
    int m_head; //下一次出队位置
    int m_tail; //下一次入队位置

主要实现接口:

enqueue()元素入队
front()返回队头元素
dequeue()元素出队

初始时队列为空,m_headm_tail指向同一个位置,m_length为0
在这里插入图片描述

入队示意:

在这里插入图片描述

可以看出队列满时m_headm_tail指向的位置也相同,此时通过m_length判断队列是满(N)或空(0)

出队示意:

在这里插入图片描述

通过示意图分析,实现思路如下:

如何入队?

使用enqueue()接口

  1. 入队从队尾进,只看m_tail(下一次入队位置)和m_length(队列元素个数)
  2. 元素入队后m_tail位置循环加1,m_length自增1,m_length等于最大容量 N 时队列满

如何获取队头元素?

使用front()接口

返回队头下标m_head对应元素即可

如何出队?

使用dequeue()接口

  1. 出队从队头出,只看m_head(下一次出队位置)和m_length(队列元素个数)
  2. 元素出队后m_head位置循环加1,m_length自减1,m_length等于 0 时队列空
#include<iostream>
#include<cassert>

template<typename T, int N>
class ArrayQueue
{
private:
    T m_array[N];
    int m_length;
    int m_head;
    int m_tail;

public:
    ArrayQueue() :
    	m_length(0),
    	m_head(0),
    	m_tail(0)
    {}
    
    ~ArrayQueue() = default;

    void enqueue(const T& e)
    {
        if ( m_length < N )
        {
            m_array[m_tail] = e;
            m_tail = (m_tail + 1) % N;
            m_length++;
        }
    }

    T front() const
    {
        if ( m_length > 0 )
        {
            return m_array[m_head];
        }
        else
        {
            throw std::out_of_range("no element in queue ...");
        }
    }

    void dequeue()
    {
        if ( m_length > 0 )
        {
            m_head = (m_head + 1) % N;
            m_length--;
        }
    }

    void clear()
    {
        m_head = 0;
        m_tail = 0;
        m_length = 0;
    }

    int capacity() const
    {
        return N;
    }

    int length() const
    {
        return m_length;
    }
};

int main()
{
    ArrayQueue<int, 5> array_queue;

    for ( int i = 5; i > 0; --i )
    {
        array_queue.enqueue(i);
    }

    for ( int i = 0; i < 5; ++i )
    {
        std::cout << array_queue.front() << " ";
        array_queue.dequeue();
    }
    std::cout << std::endl;

    return 0;
}
//运行结果
5 4 3 2 1 

参考

  • 狄泰软件学院:数据结构实战开发
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值