链表练习

一个简单实用的链表,有时间再完善下其他功能:

#ifndef LINKLIST_H
#define LINKLIST_H

template <typename T>
struct SLink
{
    T m_tData;
    SLink* m_pNetx;
};

template <typename T>
class CLinkList
{
    template <typename R>
    friend std::ostream& operator<< ( std::ostream& os, const CLinkList<R>& list );
public:
    CLinkList()
    {
        m_pHead = new SLink<T>();
        m_pHead->m_tData = T();
        m_pHead->m_pNetx = NULL;
    }
    virtual ~CLinkList()
    {
        SLink<T>* pLink = m_pHead;
        while( pLink )
        {
            SLink<T>* pTempLink = pLink->m_pNetx;
            delete pLink, pLink = NULL;
            pLink = pTempLink;
        }
    }
    //先插入的数据在链表后面
    bool addLink( const T& val )
    {
        SLink<T>* pNewLink = new SLink<T>();
        if( !pNewLink )
        {
            return false;
        }
        pNewLink->m_tData = val;
        pNewLink->m_pNetx = m_pHead->m_pNetx;

        m_pHead->m_pNetx = pNewLink;

        return true;
    }
    //依次将每一个节点插入到head后面
    void reverse()
    {
        SLink<T>* pLink = m_pHead->m_pNetx;
        SLink<T>* pTempLink = NULL;
        //置head的next为空,
        m_pHead->m_pNetx = NULL;
        while( pLink )
        {
            //记录下一个节点
            pTempLink = pLink->m_pNetx;

            //当前节点插入头节点之后,修改其next为之前的头结点的next
            pLink->m_pNetx = m_pHead->m_pNetx;
            m_pHead->m_pNetx = pLink;

            pLink = pTempLink;
        }
    }
protected:
private:
    SLink<T>* m_pHead;
};

template <typename R>
std::ostream& operator<< ( std::ostream& os, const CLinkList<R>& list )
{
    SLink<R>* pLink = list.m_pHead->m_pNetx;
    while( pLink )
    {
        os << pLink << "==>" << pLink->m_tData << std::endl;
        pLink = pLink->m_pNetx;
    }
    return os;
}
#endif // LINKLIST_H