C++單向鏈表實(shí)現(xiàn)代碼解讀
作者:佚名
C++單向鏈表的實(shí)現(xiàn)的具體操作步驟將會(huì)在這篇文章中以代碼方式為大家呈現(xiàn)。朋友們可以以此為學(xué)習(xí)參考對(duì)象,進(jìn)一步掌握這一應(yīng)用技巧。
C++編程語言是一款應(yīng)用廣泛的計(jì)算機(jī)應(yīng)用語言。我們?cè)谶@篇文章中為大家介紹的是關(guān)于C++單向鏈表的實(shí)現(xiàn)方法。希望初學(xué)者們可以通過本文介紹的內(nèi)容充分掌握這方面的知識(shí),并從中體驗(yàn)到這款語言功能的強(qiáng)大。
C++單向鏈表實(shí)現(xiàn)代碼:
- #include < iostream>
- using namespace std;
- template < class T>
- struct node
- {
- //public:
- // 結(jié)構(gòu)體成員默認(rèn)就是public的
- T data;
- node< T> *next;
- };
- //typedef struct node NODE;
- //typedef NODE *NODEPTR;
- //typedef后面要跟具體的類類型,而不是一個(gè)類模版。eg: typedef node< T>
NODE (C++中,實(shí)例化結(jié)構(gòu)體時(shí)struct可省略)- template < class T>
- class list
- {
- public:
- //以下三個(gè)函數(shù)要供外部調(diào)用,所以要聲明為public,class默認(rèn)為private。
- /*
- void creat(T &p);
- void print(T p);
- void destroy(T &p);
- */
- //這三個(gè)函數(shù)的參數(shù)有問題,按照下文的實(shí)現(xiàn),我認(rèn)為應(yīng)改為如下:
- void creat(T *p);
- void print(T *p);
- void destroy(T *p);
- };
- template< class A>
- //void creat(A &p)
- void list< A>::creat(A *p)
- {
- //class node *q;
- //形參里的A就是這個(gè)程序的node類型
- char ch = 0; //下數(shù)第4行cin>>ch 中的ch未定義,在此補(bǔ)充
- A *q = NULL;
- q=p; //必須新增這一句,q用于以后的動(dòng)態(tài)分配
- cout< < "input"< < endl;
- cin>>ch;
- // if(!p) //這個(gè)if放在while里會(huì)影響效率,故移到while外邊,
改過程序之后,實(shí)際上用不著了- // {
- //p=new struct node;
- //語法錯(cuò)誤,形參里的A就是這個(gè)程序的node類型
- // p = new A();
- if(ch!='#')
- p->data=ch;
- // }
- cin>>ch;
- while(ch!='#')
- {
- //q->next=new class node;
- //語法錯(cuò)誤,形參里的A就是這個(gè)程序的node類型
- q->next = new A();
- //q->next=ch;
- //這句應(yīng)該是給data賦值
- q->next->data = ch;
- qq = q->next; //必須新增這一句,q用于以后的動(dòng)態(tài)分配
- cin>>ch;
- }
- q->next=NULL;
- }
- template < class T>
- void list< T>::print(T *p)
- {
- if(p)
- {
- cout< < p->data< < " ";
- print(p->next);
- }
- }
- template < class T>
- void list< T>::destroy(T *p)
- {
- if(p)
- {
- destroy(p->next);
- delete p->next;
- }
- }
- int main()
- {
- // NODEPTR p;
- node< int> p;
- // list L; 模版要有參數(shù)
- list< node< int> > L;
- L.creat(&p);
- cout < < endl < < endl < < "show:" < < endl;
- L.print(&p);
- L.destroy(&p);
- return 0;
- }
實(shí)現(xiàn)C++單向鏈表時(shí),程序使用了指針,如果改用引用更好些。
【編輯推薦】
責(zé)任編輯:曹凱
來源:
博客園