#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; ch = 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 <iostream> #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 <<endl; queue.pop(c); cout << c <<endl; queue.pop(c); cout << c <<endl; queue.push(9); bool re = queue.pop(c); cout << re <<":"<< c <<endl; re = queue.pop(c); cout << re << ":"<< c <<endl; re = queue.pop(c); cout << re <<":" << c <<endl; getchar(); }
模板化处理后,如下:
#ifndef __QUEUE__ #define __QUEUE__ template<class T> class 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<class T> CQueue<T>::CQueue(int nCount) { m_pData = new T[nCount]; m_nHead = m_nTail = 0; m_nCount = nCount; } template<class T> void CQueue<T>::push(const T & value) { if(!isFull()) { m_pData[m_nTail++] = value; if(m_nTail >= m_nCount) m_nTail = 0; } } template<class T> bool CQueue<T>::pop (T & ch) { if(isEmpty())return false; ch = m_pData[m_nHead++]; if(m_nHead >= m_nCount) m_nHead = 0; return true; } template<class T> bool CQueue<T>::isFull() { return ((m_nTail+1)%m_nCount == m_nHead); } template<class T> bool CQueue<T>::isEmpty() { return m_nHead == m_nTail; } #endif
时间: 2024-10-10 16:42:22