首页 > 代码库 > 链式队列的实现

链式队列的实现

QueueNode.h

template <typename Type> class LinkQueue;template< class Type >class QueueNode{private:    friend class LinkQueue<Type>;    friend ostream& operator<<(ostream& out, const LinkQueue<Type>& q);  //函数要访问QueueNode的私有成员, 因此要在此声明    QueueNode(const Type t, QueueNode<Type>*pnext=NULL):item(t), next(pnext){}private:    Type item;    QueueNode<Type>* next;};

LinkQueue.h

#include "QueueNode.h"template<typename Type>class LinkQueue{    friend ostream& operator<<(ostream& out, const LinkQueue<Type>& q) //de    {        QueueNode<Type>* tmp = q.m_pfront;        while(tmp!=NULL)        {            out<<tmp->item<<"-->";            tmp = tmp->next;        }        cout<<"NULL"<<endl;        return out;    }public:    LinkQueue():m_prear(NULL), m_pfront(NULL){};private:    QueueNode<Type>* m_prear,* m_pfront;public:    bool isEmpty() const    {        return m_pfront==NULL;    }    void Append(const Type t)    {        if (isEmpty())        {            m_pfront = m_prear = new QueueNode<Type>(t);        }        else        {            m_prear->next = new QueueNode<Type>(t);            m_prear = m_prear->next;        }    }    Type getFront() const    {        if(isEmpty())        {            cout<<"There is no elements!"<<endl;            exit(1);        }        return m_pfront->item;    }    void popFront()    {        if (isEmpty())        {            cout<<"There is no elements!"<<endl;        }        QueueNode<Type>* tmp = m_pfront;        m_pfront = m_pfront->next;        delete tmp;    }    void clear()    {        QueueNode<Type>* tmp ;        while(m_pfront)        {            tmp = m_pfront;            m_pfront = m_pfront->next;            delete tmp;        }    }};

test.cpp

#include<iostream>using namespace std;#include "LinkQueue.h"int main(){    LinkQueue<int> linkQueueInt;    linkQueueInt.Append(1);    linkQueueInt.Append(2);    linkQueueInt.Append(3);    linkQueueInt.Append(4);    linkQueueInt.Append(5);    cout<<linkQueueInt<<endl;}

 

链式队列的实现