您好,登錄后才能下訂單哦!
#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 <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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。