当前位置:   article > 正文

C++数组实现队列_数组实现队列c++

数组实现队列c++

C++数组实现队列

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

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

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

主要实现接口:

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 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90

参考

  • 狄泰软件学院:数据结构实战开发
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/756385
推荐阅读
相关标签
  

闽ICP备14008679号