您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
#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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。