C 單鏈表的設計與實現

2021-07-12 04:01:23 字數 1777 閱讀 6912

單鏈表是一種常見的資料結構,c++不同於c的語言特性是封裝、繼承和多型。若要實現單鏈表,首先我們要明確什麼是單鏈表,鍊錶是由乙個或多個節點構成的,實現鍊錶的資料結構,我們首先是要明確的是什麼是節點。

節點是由資料+該節點型別的指標組成的,如下:

class seqnode

private:

seqnode* _next;

datetype _data;

};

鍊錶的形成是節點->節點->.....->null;

所以,新手經常不會寫鍊錶,解釋沒有明確節點這種資料結構。有了節點我們便可通過修改節點中的_next指標使其成為鍊錶,這裡我們建立出煉錶類及宣告一些鍊錶類的基本操作:

class seqlist

~seqlist()

void pushback(datetype x);

void popback();

void pushfront(datetype x);

void popfront();

void erase(datetype x);

void insert(datetype x,size_t pos);

private:

void _clear()//用來釋放鍊錶每乙個節點的函式,對其進行封裝,以便實現以後的一些操作 }

seqnode*_head;//頭指標

seqnode*_tail;//尾指標

};

在這裡我沒有寫出這兩個類的拷貝構造以及賦值運算子的過載,鍊錶的複製可以用深淺拷貝兩種方式實現,節點的複製是需要看datetype的型別以及所儲存內容來決定,例如每個節點都存乙個在堆上開闢的字串,在這裡我預設儲存為整形,所以並不涉及深淺拷貝的問題。

其餘已宣告函式的實現:

#include"slist.h"

#includevoid seqlist::pushback(datetype x)

else }

void seqlist::popback()

else

cur->_next = null;

delete _tail;

_tail = cur; }}

void seqlist::pushfront(datetype x)

else }

void seqlist::popfront()

else }

void seqlist::insert(datetype x, size_t pos)

else

tmp->_next = cur->_next;

cur->_next = tmp; }}

void seqlist::erase(datetype x)

if (_head->_next != null)

prev = prev->_next;

cur = prev->_next;

} }}

測試用例:

#includeusing namespace std;

#include"slist.h"

void test1()

void test2()

int main()

如有不足之處,希望指正。

本文出自 「pawnsir的it之路」 部落格,請務必保留此出處

單鏈表的c 實現

node類標頭檔案 ifndef node h define node h include include using namespace std class node endif node類cpp include node.h using namespace std 過載 運算子 ostream ...

單鏈表的C 實現

include using namespace std struct node class list void insertlist int adata,int bdata void deletelist int adata void outputlist node gethead void lis...

C 單鏈表的實現

include include include include using namespace std typedef struct student node node create 建立單鏈表 else cycle 0 head head next p next null coutreturn h...