码迷,mamicode.com
首页 > 其他好文 > 详细

链式队列的实现

时间:2015-01-22 13:13:27      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

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;



}

 

链式队列的实现

标签:

原文地址:http://www.cnblogs.com/aituming/p/4241312.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!