最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C++圖解單向鏈表類(lèi)模板和iterator迭代器類(lèi)模版詳解

 更新時(shí)間:2022年02月25日 16:51:08   作者:諾謙  
這篇文章主要為大家詳細(xì)介紹了C++圖解單向鏈表類(lèi)模板和iterator迭代器類(lèi)模版,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助

鏈表用來(lái)構(gòu)建許多其它數(shù)據(jù)結(jié)構(gòu),如堆棧,隊(duì)列和他們的派生。

對(duì)于非線(xiàn)性的鏈表,可以參見(jiàn)相關(guān)的其他數(shù)據(jù)結(jié)構(gòu),例如二叉樹(shù)、圖等。

1.鏈表介紹

常見(jiàn)的線(xiàn)性鏈表分為三種

單鏈表: 每個(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指針, 每次訪(fǎng)問(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)開(kāi)始遍歷,通過(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)開(kāi)始遍歷,通過(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):  重寫(xiě)<<操作符,方便尾部追加數(shù)據(jù)

int indexOf(const T &value, int from =0) : 在鏈表中向前查找value所在的索引號(hào).默認(rèn)從from索引號(hào)0(表頭)開(kāi)始.如果未找到則返回-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開(kāi)始查找,returns 3
cout<<"from index0 find 3 :"<<list.indexOf(3)<<endl;    //returns -1

打印效果如下所示:

本章SingleLinkedList.h的整個(gè)代碼實(shí)現(xiàn)如下所示(包含迭代器類(lèi)):

#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)類(lèi)模板*/
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)值
};
/*單鏈表類(lèi)模板*/
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(表頭)開(kāi)始.如果未找到則返回-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;
    }
};
/*單鏈表迭代器類(lèi)模板*/
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í)又稱(chēng)光標(biāo)(cursor)是程序設(shè)計(jì)的軟件設(shè)計(jì)模式,可在容器對(duì)象(container,例如鏈表或數(shù)組)上遍訪(fǎng)的接口,設(shè)計(jì)人員無(wú)需關(guān)心容器對(duì)象的內(nèi)存分配的實(shí)現(xiàn)細(xì)節(jié)。

3.1 為什么要實(shí)現(xiàn)一個(gè)迭代器?

比如我們剛剛寫(xiě)的遍歷鏈表代碼:

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)定位到開(kāi)頭位置
  • T& move(int i): 將迭代器當(dāng)前光標(biāo)定位到i位置處,并返回當(dāng)前位置的值

迭代器類(lèi)實(shí)現(xiàn)如下所示:

/*單鏈表迭代器類(lèi)模板*/
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)的全排列算法示例

    這篇文章主要介紹了C++簡(jiǎn)單實(shí)現(xiàn)的全排列算法,結(jié)合實(shí)例形式分析了C++排序操作的實(shí)現(xiàn)技巧,需要的朋友可以參考下
    2017-07-07
  • 淺析c++中new和delete的用法

    淺析c++中new和delete的用法

    以下是對(duì)c++中new和delete的用法進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過(guò)來(lái)參考下
    2013-09-09
  • C++右值引用問(wèn)題解決

    C++右值引用問(wèn)題解決

    本文主要介紹了C++右值引用問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • c語(yǔ)言socket多線(xiàn)程編程限制客戶(hù)端連接數(shù)

    c語(yǔ)言socket多線(xiàn)程編程限制客戶(hù)端連接數(shù)

    這篇文章主要介紹了c語(yǔ)言socket多線(xiàn)程編程,可以限制客戶(hù)端連接數(shù),大家參考使用吧
    2013-12-12
  • C++中的map使用方法詳解

    C++中的map使用方法詳解

    C++中的map是一種關(guān)聯(lián)容器,用于存儲(chǔ)鍵值對(duì)。它提供了一種非常高效的方法來(lái)快速查找特定的值,并且允許我們根據(jù)鍵來(lái)排序和遍歷數(shù)據(jù)。在本文中,我們將深入了解C++中的map以及如何使用它來(lái)提高程序的效率,感興趣的朋友可以參考下
    2023-05-05
  • Qt專(zhuān)欄之模態(tài)與非模態(tài)對(duì)話(huà)框的實(shí)現(xiàn)

    Qt專(zhuān)欄之模態(tài)與非模態(tài)對(duì)話(huà)框的實(shí)現(xiàn)

    這篇文章主要介紹了Qt專(zhuān)欄之模態(tài)與非模態(tài)對(duì)話(huà)框的實(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í)例詳解

    這篇文章主要介紹了C++實(shí)現(xiàn) 單例模式實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下
    2017-05-05
  • C++ 中malloc()和free()函數(shù)的理解

    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中項(xiàng)目的構(gòu)建配置和運(yùn)行設(shè)置的步驟

    使用 Qt Creator 集成開(kāi)發(fā)環(huán)境構(gòu)建和運(yùn)行程序是一件非常簡(jiǎn)單的事情,一個(gè)按鈕或者一個(gè)快捷鍵搞定全部,本文主要介紹了Qt creator中項(xiàng)目的構(gòu)建配置和運(yùn)行設(shè)置的步驟,感興趣的小伙伴們可以參考一下
    2021-11-11
  • c++大數(shù)階乘的實(shí)現(xiàn)方法

    c++大數(shù)階乘的實(shí)現(xiàn)方法

    本篇文章對(duì)c++的大數(shù)階乘進(jìn)行了代碼示例的介紹。需要的朋友參考下
    2013-05-05

最新評(píng)論

九龙城区| 潢川县| 丘北县| 灵丘县| 沂源县| 呼玛县| 灌云县| 临武县| 佛冈县| 德兴市| 青岛市| 比如县| 隆安县| 青神县| 嘉鱼县| 汝南县| 大安市| 边坝县| 开原市| 台南市| 长岭县| 金山区| 资兴市| 司法| 德安县| 平潭县| 黎城县| 旺苍县| 桃江县| 都兰县| 五台县| 大邑县| 河间市| 庆安县| 台安县| 宣汉县| 常州市| 高清| 奇台县| 朝阳区| 武鸣县|