用模板寫通用連結串列的方法之一
阿新 • • 發佈:2019-01-28
用模板寫通用連結串列方法之一
以前老師要我們用C語言寫通用連結串列,由於是通用嘛,資料的輸入輸出就不一樣,所以得連結串列演算法和資料分離開來.最近學了多型,可以用基類指標指向派生類的方式寫通用連結串列,實現起來更加方便.今天又給我們講了一個另類的模板的方法.
// ListTtest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Student.h" //模板不能分多檔案寫 template class CList { class CNode { public: T m_Data; CNode *m_pLast; CNode *m_pNext; }; public: CList(); ~CList(); T* Create(); T* Add(); void ClearList(); private: CNode *m_pHead; CNode *m_pLast; }; template CList::CList() { m_pHead = NULL; m_pLast = NULL; } template CList::~CList() { ClearList(); } template T* CList::Create() { if(NULL != m_pHead) { return NULL; } m_pHead = new CNode; if(NULL == m_pHead) { return NULL; } m_pHead->m_pNext = NULL; m_pHead->m_pLast = NULL; m_pLast = m_pHead; return &(m_pHead->m_Data); } template T* CList::Add() { if(NULL == m_pHead) { return NULL; } CNode *pNew = new CNode; pNew->m_pLast = m_pLast; pNew->m_pNext = NULL; m_pLast = pNew; return &(pNew->m_Data); } template void CList::ClearList() { CNode *pTemp = m_pHead; while(NULL != pTemp) { m_pHead = m_pHead->m_pNext; delete pTemp; pTemp = m_pHead; } } int main(int argc, char* argv[]) { //CList *pObj; 定義為指標時,由於沒有分配空間,所以呼叫Create函式的時候會崩潰;可以這麼寫 //(pObj->Create())->Input(); CList *pObj = new CList; (pObj->Create())->Input(); CList Obj; Obj.Create()->Input(); return 0; }
// Student.cpp: implementation of the CStudent class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Student.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CStudent::CStudent() { m_szNum[0] = ' '; m_nAge = 0; } CStudent::~CStudent() { } void CStudent::Input() { cout<<"Please input student number:"; cin>>m_szNum; cout<<"Please input student age:"; cin>>m_nAge; }
// Student.h: interface for the CStudent class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_STUDENT_H__E0DF041B_A9A3_46F4_B7E0_1CAA9AF3D392__INCLUDED_) #define AFX_STUDENT_H__E0DF041B_A9A3_46F4_B7E0_1CAA9AF3D392__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CStudent { public: CStudent(); ~CStudent(); void Input(); private: char m_szNum[20]; int m_nAge; }; #endif // !defined(AFX_STUDENT_H__E0DF041B_A9A3_46F4_B7E0_1CAA9AF3D392__INCLUDED_)
記錄下老師講的知識點,方便以後回顧,又感覺自己萌萌噠!