以下是实现:
template <typename T> class QueueNode { public: QueueNode(T data) :m_data(data), m_pNext(nullptr) {} QueueNode(T data, QueueNode* next) :m_data(data), m_pNext(next) {} T getData() { return m_data; } QueueNode* getNext() { return m_pNext; } void setData(T d) { m_data = d; } void setNext(QueueNode* n) { m_pNext = n; } private: int m_data; //数据 QueueNode* m_pNext; //下个数据 }; template <typename T> class DoubleQueue { public: DoubleQueue():m_pFront(nullptr), m_pBack(nullptr){} void push_back(T data) { if (m_pBack) { QueueNode<T>* tmp = new QueueNode<T>(data, m_pBack); m_pBack->setNext(tmp); m_pBack = tmp; } else {//null m_pBack = new QueueNode<T>(data); m_pFront = m_pBack; } } void push_front(T data) { if (m_pFront) { QueueNode<T>* tmp = new QueueNode<T>(data, m_pFront); m_pFront->setNext(tmp); m_pFront = tmp; } else {//null m_pFront = new QueueNode<T>(data); m_pBack = m_pFront; } } T pop_back() { if (m_pBack) { T retValue = m_pBack->getData(); QueueNode<T>* freeObj = m_pBack; m_pBack = m_pBack->getNext(); if (m_pBack == nullptr) m_pFront = nullptr; delete freeObj; freeObj = nullptr; return retValue; } return T(); } T pop_front() { if (m_pFront) { T retValue = m_pFront->getData(); QueueNode<T>* freeObj = m_pFront; m_pFront = m_pFront->getNext(); if (m_pFront == nullptr) m_pBack = nullptr; delete freeObj; freeObj = nullptr; return retValue; } } T back() {return m_pBack->getData();} T front() { return m_pFront->getData(); } private: QueueNode<T>* m_pFront; QueueNode<T>* m_pBack; };