C++圖解單向鏈表類模板和iterator迭代器類模版詳解
鏈表用來(lái)構(gòu)建許多其它數(shù)據(jù)結(jié)構(gòu),如堆棧,隊(duì)列和他們的派生。
對(duì)于非線性的鏈表,可以參見相關(guān)的其他數(shù)據(jù)結(jié)構(gòu),例如二叉樹、圖等。
1.鏈表介紹
常見的線性鏈表分為三種
單鏈表: 每個(gè)結(jié)點(diǎn)都含有指向其后繼結(jié)點(diǎn)的地址信息

雙向鏈表: 每個(gè)結(jié)點(diǎn)都有指向其前驅(qū)結(jié)點(diǎn)和后繼結(jié)點(diǎn)的地址信息

循環(huán)雙向鏈表: 在雙向鏈表的基礎(chǔ)上,將數(shù)據(jù)結(jié)點(diǎn)頭的前驅(qū)信息保存數(shù)據(jù)結(jié)點(diǎn)尾部地址,數(shù)據(jù)結(jié)點(diǎn)尾部的后驅(qū)信息保存數(shù)據(jù)結(jié)點(diǎn)頭地址、

鏈表中包含的關(guān)鍵詞如下所示:
- 鏈表頭: 也就是head指針, 每次訪問(wèn)鏈表時(shí)都可以從這個(gè)頭指針依次遍歷鏈表中的每個(gè)元素
- 頭結(jié)點(diǎn): 數(shù)據(jù)內(nèi)容無(wú)效,指向數(shù)據(jù)結(jié)點(diǎn)
- 數(shù)據(jù)結(jié)點(diǎn): 存儲(chǔ)數(shù)據(jù)元素的結(jié)點(diǎn)
- 尾結(jié)點(diǎn):數(shù)據(jù)內(nèi)容無(wú)效,位于數(shù)據(jù)結(jié)點(diǎn)尾部,標(biāo)志最后一個(gè)結(jié)點(diǎn)
對(duì)于鏈表而言,鏈表頭必須存在。而頭結(jié)點(diǎn)和尾結(jié)點(diǎn)在有些鏈表中是不存在的,但是擁有頭結(jié)點(diǎn)會(huì)有很大的好處
擁有頭結(jié)點(diǎn)的好處:
每次插入刪除時(shí),無(wú)需判斷是否為第一個(gè)結(jié)點(diǎn)(對(duì)于無(wú)頭結(jié)點(diǎn)的鏈表,每次都要判斷如果是第一個(gè)結(jié)點(diǎn),需要將前驅(qū)信息設(shè)置為鏈表頭,并且將鏈表頭的后繼信息設(shè)置為第一個(gè)結(jié)點(diǎn))
如果是雙向循環(huán)鏈表(下章實(shí)現(xiàn)),我們可以通過(guò)頭結(jié)點(diǎn)的前驅(qū)節(jié)點(diǎn)輕松獲取到最后一個(gè)數(shù)據(jù)結(jié)點(diǎn),從而實(shí)現(xiàn)append函數(shù)進(jìn)行尾部插入結(jié)點(diǎn),無(wú)需每次遍歷鏈表至末尾再插入結(jié)點(diǎn).
1.1 單鏈表插入某個(gè)節(jié)點(diǎn)流程
如下圖所示:

從頭結(jié)點(diǎn)開始遍歷,通過(guò)要插入的索引號(hào)-1找到pre指針后,代碼如下所示:
Node* pre = getNode(i-1); // 獲取上個(gè)節(jié)點(diǎn) Node* node = new Node(); // new一個(gè)新節(jié)點(diǎn) node->data = value; // 設(shè)置data數(shù)據(jù)元素 node->next = pre->next; // 將新節(jié)點(diǎn)的next鏈接到下個(gè)節(jié)點(diǎn) pre->next = node; // 將前個(gè)節(jié)點(diǎn)的next鏈接到創(chuàng)建的新節(jié)點(diǎn) m_length += 1;
1.2 單鏈表刪除某個(gè)節(jié)點(diǎn)流程
如下圖所示:

從頭結(jié)點(diǎn)開始遍歷,通過(guò)要?jiǎng)h除的索引號(hào)-1找到current指針的前一個(gè)結(jié)點(diǎn)pre后,代碼如下所示:
Node* pre = getNode(i-1); Node* current = pre->next; // 獲取要?jiǎng)h除的節(jié)點(diǎn) pre->next = current->next; // 將當(dāng)前節(jié)點(diǎn)的下個(gè)節(jié)點(diǎn)鏈接到前一個(gè)的next中 delete current; // delete空閑的節(jié)點(diǎn) m_length -= 1;
1.3 單鏈表清除所有節(jié)點(diǎn)流程
代碼如下所示:
while(m_header.next) {
Node* node = m_header.next;
m_header.next = node->next;
delete node;
}
m_length = 0;2.實(shí)現(xiàn)單鏈表
需要實(shí)現(xiàn)的函數(shù):
int length() : 獲取鏈表數(shù)據(jù)長(zhǎng)度
void clear() : 清空鏈表所有數(shù)據(jù)
Node* getNode(int i): 獲取i處的節(jié)點(diǎn)
bool insert(int i, const T& value) : 在索引號(hào)i處插入一個(gè)新的數(shù)據(jù)
bool remove(int i) : 刪除鏈表中索引號(hào)i所在的數(shù)據(jù)
T get(int i): 獲取i處的數(shù)據(jù)
bool set(int i, const T& value): 設(shè)置i處的數(shù)據(jù)
void append(const T &value) :在鏈表尾部追加一個(gè)新的數(shù)據(jù)
void prepend(const T &value) : 在鏈表頭部插入一個(gè)新的數(shù)據(jù)
void clear() : 清空鏈表內(nèi)容
LinkedList& operator << (const T& value): 重寫<<操作符,方便尾部追加數(shù)據(jù)
int indexOf(const T &value, int from =0) : 在鏈表中向前查找value所在的索引號(hào).默認(rèn)從from索引號(hào)0(表頭)開始.如果未找到則返回-1.
2.1indexOf()函數(shù)示例如下所示:
LinkedList<int> list; list << 1 << 2 << 4 << 2 << 6; cout<<"from index0 find 2 :"<<list.indexOf(2)<<endl; //returns 1 cout<<"from index1 find 2 :"<<list.indexOf(2, 1)<<endl; //returns 1 cout<<"from index2 find 2 :"<<list.indexOf(2, 2)<<endl; //從索引號(hào)2開始查找,returns 3 cout<<"from index0 find 3 :"<<list.indexOf(3)<<endl; //returns -1
打印效果如下所示:

本章SingleLinkedList.h的整個(gè)代碼實(shí)現(xiàn)如下所示(包含迭代器類):
#ifndef SingleLinkedLIST_H
#define SingleLinkedLIST_H
#include "throw.h"
// throw.h里面定義了一個(gè)ThrowException拋異常的宏,如下所示:
//#include <iostream>
//using namespace std;
//#define ThrowException(errMsg) {cout<<__FILE__<<" LINE"<<__LINE__<<": "<<errMsg<<endl; (throw errMsg);}
/*鏈表節(jié)點(diǎn)類模板*/
template <typename T>
struct SingleLinkedNode
{
inline SingleLinkedNode(){ }
inline SingleLinkedNode(const T &arg): value(arg) { }
SingleLinkedNode *next; // 后驅(qū)節(jié)點(diǎn)
T value; // 節(jié)點(diǎn)值
};
/*單鏈表類模板*/
template <class T>
class SingleLinkedList
{
protected:
typedef SingleLinkedNode<T> Node;
Node m_header; // 頭節(jié)點(diǎn)
int m_length;
public:
SingleLinkedList() { m_header.next = nullptr; m_length = 0; }
~SingleLinkedList() { clear(); }
void append(const T &value) { insert(m_length, value);}
void prepend(const T &value) {insert(0, value);}
int length() {return m_length;}
Node* begin() {return m_header.next;}
static bool rangeValid(int i,int len) {return ((i>=0) && (i<len));}
/*獲取i位置處的節(jié)點(diǎn)*/
Node* getNode(int i)
{
Node* ret = &m_header;
while((i--)>-1) { // 由于有頭節(jié)點(diǎn)所以,i為0時(shí),其實(shí)ret = m_header->n
ret = ret->next;
}
return ret;
}
/*插入一個(gè)新的節(jié)點(diǎn)*/
bool insert(int i, const T& value)
{
if (!((i>=0) && (i<=m_length))) {
ThrowException("Invalid parameter i to get value ...");
return false;
}
Node* pre = getNode(i-1);
Node* node = new Node(value); // new一個(gè)新節(jié)點(diǎn)
node->next = pre->next; // 將新節(jié)點(diǎn)的next鏈接到下個(gè)節(jié)點(diǎn)
pre->next = node; // 將前個(gè)節(jié)點(diǎn)的next鏈接到創(chuàng)建的新節(jié)點(diǎn)
m_length +=1;
return true;
}
/*刪除一個(gè)節(jié)點(diǎn)*/
bool remove(int i)
{
if (!rangeValid(i, m_length)) {
ThrowException("Invalid parameter i to get value ...");
return false;
}
Node* pre = getNode(i-1);
Node* current = pre->next; // 獲取要?jiǎng)h除的節(jié)點(diǎn)
pre->next = current->next; // 將當(dāng)前節(jié)點(diǎn)的下個(gè)節(jié)點(diǎn)鏈接到前一個(gè)的next中
delete current; // delete空閑的節(jié)點(diǎn)
m_length -=1;
return true;
}
/*獲取節(jié)點(diǎn)數(shù)據(jù)*/
T get(int i)
{
T ret;
if (!rangeValid(i, m_length)) {
ThrowException("Invalid parameter i to get value ...");
} else {
ret = getNode(i)->value;
}
return ret;
}
/*設(shè)置節(jié)點(diǎn)*/
bool set(int i, const T& value)
{
if (!rangeValid(i, m_length)) {
ThrowException("Invalid parameter i to get value ...");
return false;
}
getNode(i)->value = value;
return true;
}
void clear()
{
while(m_header.next) {
Node* node = m_header.next;
m_header.next = node->next;
delete node;
}
m_length = 0;
}
SingleLinkedList<T>& operator << (const T& value)
{
append(value);
return *this;
}
/*在鏈表中向前查找value所在的索引號(hào).默認(rèn)從from索引號(hào)0(表頭)開始.如果未找到則返回-1.*/
int indexOf(const T &value, int from =0)
{
int ret = 0;
Node* node = m_header.next;
while(node) {
if (ret >= from && node->value == value) {
return ret;
}
node = node->next;
ret+=1;
}
return -1;
}
};
/*單鏈表迭代器類模板*/
template <class T>
class SingleLinkedListIterator
{
typedef SingleLinkedNode<T> Node;
SingleLinkedList<T> *list;
Node *m_current; // 當(dāng)前指標(biāo)
public:
explicit SingleLinkedListIterator(SingleLinkedList<T> &l):list(&l) { m_current = l.begin(); }
void toBegin() { m_current = list->begin(); }
bool hasNext() { return (m_current); }
T& next() { Node *ret = m_current; m_current = m_current->next; return ret->value; }
T& value()
{
if (m_current == nullptr) {
ThrowException(" Current value is empty ...");
}
return m_current->value;
}
T& move(int i) {
if (!list->rangeValid(i, list->length())) {
ThrowException("Invalid parameter i to get value ...");
}
m_current = list->getNode(i);
return value();
}
};
#endif // SingleLinkedLIST_H測(cè)試代碼如下所示:
SingleLinkedList<int> list;
for(int i = 0; i< 5; i++)
list.append(i);
for(int i = 0; i< 5; i++)
list<<i+5;
cout<<"print:"<<endl;
cout<<"list.length:"<<list.length()<<endl;
for(int i = 0; i< list.length(); i++){
cout<<" "<<list.get(i)<<" ";
}
cout<<endl;
// 修改鏈表數(shù)據(jù)
list.set(1,100);
list.set(2,200);
list.remove(3);
list.insert(5,500);
cout<<"changed:"<<endl;
cout<<"list.length:"<<list.length()<<endl;
for(int i = 0; i< list.length(); i++){
cout<<" "<<list.get(i)<<" ";
}
cout<<endl;運(yùn)行打印:

3.實(shí)現(xiàn)一個(gè)迭代器來(lái)優(yōu)化鏈表遍歷
迭代器(iterator)有時(shí)又稱光標(biāo)(cursor)是程序設(shè)計(jì)的軟件設(shè)計(jì)模式,可在容器對(duì)象(container,例如鏈表或數(shù)組)上遍訪的接口,設(shè)計(jì)人員無(wú)需關(guān)心容器對(duì)象的內(nèi)存分配的實(shí)現(xiàn)細(xì)節(jié)。
3.1 為什么要實(shí)現(xiàn)一個(gè)迭代器?
比如我們剛剛寫的遍歷鏈表代碼:
for(int i = 0; i< list.length(); i++){ // 時(shí)間復(fù)雜度為O(n)
cout<<" "<<list.get(i)<<" "; // get函數(shù)的時(shí)間復(fù)雜度為O(n)
}每次for循環(huán)調(diào)用鏈表的get時(shí),都會(huì)重復(fù)去遍歷鏈表,所以遍歷一個(gè)鏈表需要的時(shí)間復(fù)雜度為O(n^2),所以我們需要實(shí)現(xiàn)迭代器來(lái)優(yōu)化鏈表遍歷
迭代器需要實(shí)現(xiàn)以下幾個(gè)函數(shù):
bool hasNext():是否有下個(gè)節(jié)點(diǎn)T &next():移動(dòng)光標(biāo)到下一個(gè)節(jié)點(diǎn),并返回之前的值T &value():獲取當(dāng)前光標(biāo)的節(jié)點(diǎn)數(shù)據(jù)void toBegin():將迭代器的光標(biāo)定位到開頭位置T& move(int i):將迭代器當(dāng)前光標(biāo)定位到i位置處,并返回當(dāng)前位置的值
迭代器類實(shí)現(xiàn)如下所示:
/*單鏈表迭代器類模板*/
template <class T>
class SingleLinkedListIterator
{
typedef SingleLinkedNode<T> Node;
SingleLinkedList<T> *list;
Node *m_current; // 當(dāng)前指標(biāo)
public:
explicit SingleLinkedListIterator(SingleLinkedList<T> &l):list(&l) { m_current = l.begin(); }
void toBegin() { m_current = list->begin(); }
bool hasNext() { return (m_current); }
T& next() { Node *ret = m_current; m_current = m_current->next; return ret->value; }
T& value()
{
if (m_current == nullptr) {
ThrowException(" Current value is empty ...");
}
return m_current->value;
}
T& move(int i) {
if (!list->rangeValid(i, list->length())) {
ThrowException("Invalid parameter i to get value ...");
}
m_current = list->getNode(i);
return value();
}
};示例代碼如下所示:
SingleLinkedList<int> list;
list<<1<<4<<5<<6<<8;
SingleLinkedListIterator<int> it(list);
cout<<"print:"<<endl;
cout<<"list.length:"<<list.length()<<endl;
while (it.hasNext()) // 通過(guò)迭代器讓時(shí)間復(fù)雜度為O(n)
cout<<it.next()<<endl;
cout<<endl;
cout<<"moved:"<<endl;
it.move(2);
while (it.hasNext()) // 通過(guò)迭代器讓時(shí)間復(fù)雜度為O(n)
cout<<it.next()<<endl;打印如下所示:

總結(jié)
本篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
C++簡(jiǎn)單實(shí)現(xiàn)的全排列算法示例
這篇文章主要介紹了C++簡(jiǎn)單實(shí)現(xiàn)的全排列算法,結(jié)合實(shí)例形式分析了C++排序操作的實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-07-07
c語(yǔ)言socket多線程編程限制客戶端連接數(shù)
這篇文章主要介紹了c語(yǔ)言socket多線程編程,可以限制客戶端連接數(shù),大家參考使用吧2013-12-12
Qt專欄之模態(tài)與非模態(tài)對(duì)話框的實(shí)現(xiàn)
這篇文章主要介紹了Qt專欄之模態(tài)與非模態(tài)對(duì)話框的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
C++實(shí)現(xiàn) 單例模式實(shí)例詳解
這篇文章主要介紹了C++實(shí)現(xiàn) 單例模式實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-05-05
C++ 中malloc()和free()函數(shù)的理解
這篇文章主要介紹了C++ 中malloc()和free()函數(shù)的理解的相關(guān)資料,這里提供用法示例幫助大家理解這部分知識(shí),需要的朋友可以參考下2017-08-08
Qt creator中項(xiàng)目的構(gòu)建配置和運(yùn)行設(shè)置的步驟
使用 Qt Creator 集成開發(fā)環(huán)境構(gòu)建和運(yùn)行程序是一件非常簡(jiǎn)單的事情,一個(gè)按鈕或者一個(gè)快捷鍵搞定全部,本文主要介紹了Qt creator中項(xiàng)目的構(gòu)建配置和運(yùn)行設(shè)置的步驟,感興趣的小伙伴們可以參考一下2021-11-11

