欢迎来到我的博客https://www.cnblogs.com/veis/

https://www.cnblogs.com/veis/p/14182037.html

环形队列CQueue类模板示例

 1 #pragma once
 2 // C++环形队列类模板
 3 typedef unsigned int uint32_t; // 使用可移植数据类型
 4 template<typename DATA>
 5 class CQueue
 6 {
 7     DATA *m_pData;
 8     uint32_t m_nHead, m_nTail;
 9     uint32_t m_nCount, m_nSize;
10 public:
11 
12     inline bool isFull()
13     {// 两种情况:①头在尾前面;②尾在头前面
14         //return (m_nTail + 1 - m_nHead == m_nCount) || (m_nTail + 1 == m_nHead); // 满栈1,非满0
15         return (m_nTail + 1) % m_nCount == m_nHead;
16     }
17     inline bool isEmpty()
18     {
19         return m_nHead == m_nTail; // 空栈1,非空0
20     }
21     inline int size() const
22     {
23         return m_nSize;
24     }
25     inline DATA &front() const
26     {
27         return m_pData[m_nHead];
28     }
29     inline DATA &back() const
30     {
31         return m_pData[m_nTail-1];
32     }
33     CQueue(const uint32_t nCount = 5); // 有参构造
34     ~CQueue(); // 析构函数
35     bool push(const DATA & d); // 入列
36     bool pop(DATA & d); // 出列
37 
38 };
39 
40 template<typename DATA>
41 CQueue<DATA>::CQueue(const uint32_t nCount)
42 {
43     m_pData = new DATA[nCount]; // 指向队列的堆空间
44     //m_pData[nCount-1] = -1; // 初始化队列定位符位置为0xffffffff,便于查看,默认为0xcdcdcdcd
45     m_nHead = m_nTail = 0; // 头和尾指向首元素下标
46     m_nCount = nCount; // 记录队列长度
47     m_nSize = 0; // 记录队列中元素个数
48 }
49 
50 template<typename DATA>
51 CQueue<DATA>::~CQueue()
52 {
53     m_nHead = m_nTail = 0;
54     m_nCount = 0;
55     m_nSize = 0;
56     delete[]m_pData;
57 }
58 
59 template<typename DATA>
60 bool CQueue<DATA>::push(const DATA &d)
61 {
62     if (isFull())
63         return false;
64     ++m_nSize;
65     //if (m_nTail == m_nCount) // 入列之前判断是否到了队尾
66     //    m_nTail = 0;
67     m_nTail = m_nTail % m_nCount;
68     m_pData[m_nTail++] = d;
69     return true;
70 }
71 
72 template<typename DATA>
73 bool CQueue<DATA>::pop(DATA &d)
74 {
75     if (isEmpty())
76         return false;
77     --m_nSize;
78     //if (m_nHead == m_nCount) // 出列判断是否到了队尾
79     //    m_nHead = 0;
80     m_nHead = m_nHead % m_nCount;
81     d = m_pData[m_nHead];
82     m_pData[m_nHead++] = -1; // 把出列的位置置为0xffffffff,便于调试查看
83     return true;
84 }

 

posted @ 2020-03-17 00:11  veis  阅读(399)  评论(0编辑  收藏  举报