#ifndef __QUEUE__#define __QUEUE__class CQueue{ int * m_pData; int m_nHead,m_nTail; int m_nCount; public: CQueue(int nCount=10); bool isEmpty(); bool isFull(); void push(const int & v); bool pop(int &v);};CQueue::CQueue(int nCount){ m_pData = new int[nCount]; m_nHead = m_nTail = 0; m_nCount = nCount;}void CQueue::push(const int & value){ if(!isFull()) { m_pData[m_nTail++] = value; if(m_nTail >= m_nCount) m_nTail = 0; }}bool CQueue::pop (int & value){ if(isEmpty())return false; value = m_pData[m_nHead++]; if(m_nHead >= m_nCount) m_nHead = 0; return true;}bool CQueue::isFull(){ return ((m_nTail+1)%m_nCount == m_nHead);}bool CQueue::isEmpty(){ return m_nHead == m_nTail;}#endif
调用方法如下:
#include#include "queue.h"using namespace std;int main(int argc, char* argv[]){ CQueue queue = 5; queue.push(2); queue.push(3); queue.push(4); queue.push(5); queue.push(6); queue.push(7); queue.push(8); int c = 0; queue.pop(c); cout << c < << c < << c < << re <<":"<< c < << re << ":"<< c < << re <<":" << c <
模板化处理后,如下:
#ifndef __QUEUE__#define __QUEUE__templateclass CQueue{ T * m_pData; int m_nHead,m_nTail; int m_nCount; public: CQueue(int nCount=10); bool isEmpty(); bool isFull(); void push(const T & v); bool pop(T &v);};template CQueue ::CQueue(int nCount){ m_pData = new T[nCount]; m_nHead = m_nTail = 0; m_nCount = nCount;}template void CQueue ::push(const T & value){ if(!isFull()) { m_pData[m_nTail++] = value; if(m_nTail >= m_nCount) m_nTail = 0; }}template bool CQueue ::pop (T & ch){ if(isEmpty())return false; ch = m_pData[m_nHead++]; if(m_nHead >= m_nCount) m_nHead = 0; return true;}template bool CQueue ::isFull(){ return ((m_nTail+1)%m_nCount == m_nHead);}template bool CQueue ::isEmpty(){ return m_nHead == m_nTail;}#endif