鏈表模板

來源:互聯網
上載者:User

由於工作需要,自己實現了一個鏈表的封裝。僅僅實現了基本的介面,如果有特殊需要可以通過添加代碼來實現。

//鏈表模板類. //////////////////////////////////////////////////////////
/*
  Name: 鏈表模板類
  Copyright:
  Author:
  Description:實現一個鏈表。
*/
template <typename T>
class CLinkList
{
public:
    CLinkList();
    ~CLinkList();
    void Add( T newdata );
    bool Delete( long idx );
    long GetCount();
    bool Look(long idx , T* val);
    void ClearAll();
    T* GetHead();
    T* GetTail();
private:
    T *m_pdata,*m_ptail;
};

template <typename T>
T* CLinkList<T>::GetHead()
{
    return m_pdata;
}

template <typename T>
T* CLinkList<T>::GetTail()
{
    return m_ptail;
}

template <typename T>
void CLinkList<T>::ClearAll() //清除所有。
{
    if ( NULL==m_pdata )  { return; }

    T * tmp=m_pdata;
    T * tmp2;
    while (  tmp )
    {
        tmp2 = tmp->next;
        delete tmp;
        tmp = tmp2;
    }

    m_pdata= m_ptail = NULL;

}

template <typename T>
CLinkList<T>::CLinkList(  ) //建構函式
{
    m_pdata = m_ptail = NULL;
}

template <typename T>
CLinkList<T>::~CLinkList()  ///析構
{
    if ( m_pdata )
        ClearAll();
}

template <typename T>
void CLinkList<T>::Add( T newdata ) //鏈表尾部添加一個資料
{
    if ( m_pdata ) //如果鏈表非空
    {
        T* newItem= new T;
        memcpy( newItem , &newdata , sizeof T );
        newItem->next =NULL ;
        m_ptail->next = newItem ;
        m_ptail = newItem;
    }
    else
    {
        m_pdata = new T;
        memcpy( m_pdata , &newdata,sizeof T );
        m_pdata->next = NULL;
        m_ptail = m_pdata;
    }
}

template <typename T>
bool CLinkList<T>::Delete( long idx)  //未實現
{
    return true;
}

template < typename T >
long CLinkList<T>::GetCount()  //取得資料個數
{
    long count = 0 ;
    T * tmp=m_pdata;
    while ( tmp )
    {
        count ++ ;
        tmp = tmp->next ;
    }
    return count;
}
    
template <typename T>
bool CLinkList<T>::Look( long idx , T * val ) //查看指定索引的資料
{
    long count = 0;
    T * tmp=m_pdata;
    while (  tmp )
    {
        if ( count == idx )
        {
            memcpy( val , tmp , sizeof T );
            return true;
        }

        count ++;
        tmp = tmp->next;
    }
    return false;
}

整個模板類的定義放在標頭檔中。
執行個體化該模板時,所用類型是一個結構,要有一個自身指標類型的next域。例如
typedef struct aaa
{
    double data;
    struct aaa * next;           
} MyType ;
CLinkList <MyType> mylist;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.