STL容器list的底层实现---带头结点的双向循环链表

前天看了一篇介绍STL中的list容器的文章,但是文章中只是简单的介绍说list是一个双向链表。其实list的底层实现是带头结点的双向循环链表。文章中我也利用模版编程实现了包含绝大部分list的功能的带头结点的双向循环链表,并且经过测试发现性能要比list优秀一些。

graph LR;
0[header] --next--> 1[0];
0[header] --previous--> 5[4];
1[0] --previous--> 0[header];
1[0] --next--> 2[1];
2[1] --previous--> 1[0];
2[1] --next--> 3[2];
3[2] --previous--> 2[1];
3[2] --next--> 4[3];
4[3] --previous--> 3[2];
4[3] --next--> 5[4];
5[4] -- previous--> 4[3];
5[4] --next--> 0[header];

1.list容器的end迭代器就是头结点

  • 既然说了list是带头结点的双向循环链表,而end()是尾结点下一个位置的迭代器,那么end()就应该是头结点的迭代器。这一点通过下面的代码就可以证明。

    itend()的下一个结点,即头结点的下一个结点,因此it就是首元素的迭代器。那么依次访问这个迭代器就可以顺序得到所有元素的值。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    #include <iostream>
    #include <list>
    #include <forward_list>
    using namespace std;
    int main(){
    list<int> num;
    for(int i = 0; i < 21; ++i){
    num.push_back(i);
    }
    auto it = ++num.end();
    while(it != num.end()){
    cout << *it << " ";
    ++it;
    }
    return 0;
    }
  • 运行结果也和刚刚的分析一致

2.自己利用模版编程实现带头结点的双向循环链表

  • 我利用C++的模版编程实现了一个带头结点的双向循环链表,并提供了个双向迭代器给它。实现了一些常用的方法,包括begin()end()push_back()push_front()pop_back()pop_front()等。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    #ifndef TESTLIST_TESTLIST_H
    #define TESTLIST_TESTLIST_H

    #include <sstream>
    #include <algorithm>
    #include <string>
    #include <iterator>

    //带有双指针的结构体
    template <class T>
    struct chainNode{
    //数据成员
    T element;
    chainNode<T> *previous; //前驱
    chainNode<T> *next; //后继

    //构造方法
    chainNode() {}
    chainNode(const T& element) {this->element = element;}
    chainNode(const T& element, chainNode<T>* previous, chainNode<T>* next) {
    this->element = element;
    this->previous = previous;
    this->next = next;
    }
    };

    // 参数值非法异常
    class illegalParameterValue
    {
    public:
    illegalParameterValue(std::string theMessage = "Illegal parameter value")
    {message = theMessage;}
    void outputMessage() {std::cout << message << std::endl;}
    private:
    std::string message;
    };

    // 索引异常
    class illegalIndex
    {
    public:
    illegalIndex(std::string theMessage = "Illegal index")
    {message = theMessage;}
    void outputMessage() {std::cout << message << std::endl;}
    private:
    std::string message;
    };

    //带头结点的双向循环链表类
    template <class T>
    class doublyLinkedListWithHeader {
    public:
    //构造和析构函数
    doublyLinkedListWithHeader(int initialCapacity = 10);
    ~doublyLinkedListWithHeader();
    //ADT函数
    bool empty() const {return listSize == 0;}
    int size() const { return listSize;}
    T& get(int theIndex) const;
    int indexOf(const T& theElement) const;
    void erase(int theIndex);
    void insert(int theIndex, const T& theElement);
    void output(std::ostream& out) const;
    void clear();
    void push_back(const T& theElement);

    //将索引为theIndex的元素值设置为theElement
    void set(int theIndex, const T& theElement);

    //首插入
    void push_front(const T& theElement);

    //首弹出
    void pop_front();
    //尾弹出
    void pop_back();

    //反转链表
    void reverse();

    //交换两个链表
    void swap(doublyLinkedListWithHeader<T>& theList);

    //删除索引fromIndex至toIndex之间的元素
    void removeRange(int fromIndex, int toIndex);

    //获取首尾结点
    T& front() { return headerNode->next->element;}
    T& back() { return headerNode->previous->element;}

    //判断*this是否和theList相等
    bool isEqual(const doublyLinkedListWithHeader<T>& theList) const;
    //判断*this是否小于theList
    bool isLess(const doublyLinkedListWithHeader<T>& theList) const;

    public:
    //迭代器
    class iterator {
    public:
    typedef std::bidirectional_iterator_tag iterator_category; //双向迭代器
    typedef T value_type; //迭代器指向的数据类型
    typedef T* pointer; //指针
    typedef T& reference; //引用

    //构造函数
    iterator(chainNode<T>* theNode = NULL) {node = theNode;}

    //解引用操作符
    T& operator*() const { return node->element;}
    T* operator->() const { return &node->element;}

    //迭代器加法操作
    iterator& operator++() {node = node->next; return *this;} //前加
    iterator operator++(int){ //后加
    iterator old = *this;
    node = node->next;
    return old;
    }

    //迭代器减法操作
    iterator& operator--() {node = node->previous; return *this;} //前加
    iterator operator--(int){ //后加
    iterator old = *this;
    node = node->previous;
    return old;
    }

    //相等检验
    bool operator!=(const iterator right) const { return node != right.node;}
    bool operator==(const iterator right) const { return node == right.node;}

    protected:
    chainNode<T>* node; //结点指针
    };

    //首迭代器
    iterator begin() { return iterator(headerNode->next);}

    //尾后迭代器
    iterator end() { return iterator(headerNode);}

    protected:
    void checkIndex(int theIndex) const;
    chainNode<T>* headerNode; //头结点
    int listSize; //链表长度
    };

    //构造函数
    template <class T>
    doublyLinkedListWithHeader<T>::doublyLinkedListWithHeader(int initialCapacity) {
    if(initialCapacity < 1){
    std::ostringstream s;
    s << "Initial capacity = " << initialCapacity << "Must be > 0";
    throw illegalParameterValue(s.str());
    }
    headerNode = new chainNode<T>();
    headerNode->next = headerNode;
    headerNode->previous = headerNode;
    listSize = 0;
    }

    //析构函数
    template <class T>
    doublyLinkedListWithHeader<T>::~doublyLinkedListWithHeader() {
    //删除所有元素
    while (headerNode->next != headerNode) {
    chainNode<T>* deleteNode = headerNode->next;
    headerNode->next = deleteNode->next;
    deleteNode->next->previous = headerNode;
    delete deleteNode;
    }
    }

    //检查索引是否有效
    template <class T>
    void doublyLinkedListWithHeader<T>::checkIndex(int theIndex) const {
    //确定索引theIndex在0 和 listSize - 1之间
    if(theIndex < 0 || theIndex >= listSize){
    std::ostringstream s;
    s << "index = " << theIndex << "size = " << listSize;
    throw illegalParameterValue(s.str());
    }
    }

    //取得索引theIndex上的元素
    template <class T>
    T& doublyLinkedListWithHeader<T>::get(int theIndex) const {
    //索引不存在,则抛出异常
    checkIndex(theIndex);

    //索引在前半部分
    chainNode<T>* currendNode = headerNode;
    if (theIndex < (listSize / 2)) {
    for(int i = 0; i <= theIndex; ++i)
    currendNode = currendNode->next;
    } else {
    //在后半部分
    for(int i = listSize; i > theIndex; --i)
    currendNode = currendNode->previous;
    }
    return currendNode->element;
    }

    //将索引theIndex上的元素值设为theElement
    template <class T>
    void doublyLinkedListWithHeader<T>::set(int theIndex, const T &theElement) {
    //索引不存在,则抛出异常
    checkIndex(theIndex);

    //索引在前半部分
    chainNode<T>* currendNode = headerNode;
    if (theIndex < (listSize / 2)) {
    for(int i = 0; i <= theIndex; ++i)
    currendNode = currendNode->next;
    } else {
    //在后半部分
    for(int i = listSize; i > theIndex; --i)
    currendNode = currendNode->previous;
    }
    currendNode->element = theElement;
    }

    //元素theElement第一次出现时的索引
    template <class T>
    int doublyLinkedListWithHeader<T>::indexOf(const T &theElement) const {
    //将元素theElement放入头结点
    headerNode->element = theElement;

    //在链表中搜索元素theElement
    chainNode<T>* currentNode = headerNode->next;
    int index = 0; //当前结点的索引
    while(currentNode->element != theElement){
    //移到下一个结点
    currentNode = currentNode->next;
    ++index;
    }

    //确定是否找到
    if(currentNode == headerNode)
    return -1;
    else
    return index;
    }

    //将元素theElement插入到索引theIndex的位置
    template <class T>
    void doublyLinkedListWithHeader<T>::insert(int theIndex, const T &theElement) {
    //先检查索引是否有效
    if(theIndex < 0 || theIndex > listSize){
    //无效索引
    std::ostringstream s;
    s << "index = " << theIndex << " size = " << listSize;
    throw illegalIndex(s.str());
    }
    //在前半部分插入
    chainNode<T>* p = headerNode;
    if (theIndex < (listSize / 2)) {
    //找到插入位置的前驱结点
    for(int i = 0; i < theIndex; ++i)
    p = p->next;
    } else {
    //找到插入位置的前驱结点
    chainNode<T>* p = headerNode;
    for(int i = listSize; i >= theIndex; --i)
    p = p->previous;
    }
    p->next = new chainNode<T>(theElement, p, p->next);
    p->next->next->previous = p->next;
    ++listSize;
    }

    //删除索引为theIndex的元素
    template <class T>
    void doublyLinkedListWithHeader<T>::erase(int theIndex) {
    //先检查索引是否有效
    if(theIndex < 0 || theIndex > listSize){
    //无效索引
    std::ostringstream s;
    s << "index = " << theIndex << " size = " << listSize;
    throw illegalIndex(s.str());
    }
    //在前半部分插入
    chainNode<T> *p = headerNode, *deleteNode;
    if (theIndex < (listSize / 2)) {
    //找到插入位置的前驱结点
    for(int i = 0; i < theIndex; ++i)
    p = p->next;
    deleteNode = p->next;
    } else {
    //找到插入位置的前驱结点
    chainNode<T>* p = headerNode;
    for(int i = listSize; i >= theIndex; --i)
    p = p->previous;
    deleteNode = p->next;
    }
    p->next = p->next->next;
    p->next->previous = p;
    delete deleteNode;
    --listSize;
    }

    //首插入
    template <class T>
    void doublyLinkedListWithHeader<T>::push_front(const T &theElement) {
    //空表
    if (headerNode->next == headerNode) {
    headerNode->next = new chainNode<T>(theElement, headerNode, headerNode);
    headerNode->previous = headerNode->next;
    } else {
    //非空
    headerNode->next = new chainNode<T>(theElement, headerNode, headerNode->next);
    headerNode->next->next->previous = headerNode->next;
    }
    ++listSize;
    }

    //尾插入
    template <class T>
    void doublyLinkedListWithHeader<T>::push_back(const T &theElement) {
    //空表
    if (headerNode->next == headerNode) {
    headerNode->next = new chainNode<T>(theElement, headerNode, headerNode);
    headerNode->previous = headerNode->next;
    } else {
    headerNode->previous = new chainNode<T>(theElement, headerNode->previous, headerNode);
    headerNode->previous->previous->next = headerNode->previous;
    }
    ++listSize;
    }

    //首弹出
    template <class T>
    void doublyLinkedListWithHeader<T>::pop_front() {
    //空表,直接退出
    if (headerNode->next == headerNode)
    return;

    chainNode<T>* deleteNode = headerNode->next;
    //只有一个结点
    if (deleteNode == headerNode->previous) {
    headerNode->next = headerNode;
    headerNode->previous = headerNode;
    } else {
    headerNode->next = deleteNode->next;
    deleteNode->next->previous = headerNode;
    }
    delete deleteNode;
    --listSize;
    }

    //尾弹出
    template <class T>
    void doublyLinkedListWithHeader<T>::pop_back() {
    //空表,直接退出
    if (headerNode->next == headerNode)
    return;

    chainNode<T>* deleteNode = headerNode->previous;
    //只有一个结点
    if (deleteNode == headerNode->next) {
    headerNode->next = headerNode;
    headerNode->previous = headerNode;
    } else {
    headerNode->previous = deleteNode->previous;
    deleteNode->previous->next = headerNode;
    }
    delete deleteNode;
    --listSize;
    }

    //将元素插入到输出流
    template <class T>
    void doublyLinkedListWithHeader<T>::output(std::ostream &out) const {
    for(chainNode<T>* currentNode = headerNode->next; currentNode != headerNode; currentNode = currentNode->next)
    out << currentNode->element << " ";
    }

    //重载<<运算符
    template <class T>
    std::ostream& operator<<(std::ostream& out, const doublyLinkedListWithHeader<T>& theList) {
    theList.output(out);
    return out;
    }

    //反转链表
    template <class T>
    void doublyLinkedListWithHeader<T>::reverse() {
    //交换headerNode的两个指针
    chainNode<T>* p = headerNode;
    while(p->previous != headerNode) {
    chainNode<T>* copyNode = p->next;
    p->next = p->previous;
    p->previous = copyNode;
    p = p->next;
    }
    chainNode<T>* copyNode = p->next;
    p->next = p->previous;
    p->previous = copyNode;
    p = p->next;
    }

    //交换两个链表
    template <class T>
    void doublyLinkedListWithHeader<T>::swap(doublyLinkedListWithHeader<T> &theList) {
    //交换两个链表的headerNode
    chainNode<T>* copyNode = headerNode;
    headerNode = theList.headerNode;
    theList.headerNode = copyNode;



    //交换链表长度
    int copySize = listSize;
    listSize = theList.listSize;
    theList.listSize = copySize;
    }

    //清表
    template <class T>
    void doublyLinkedListWithHeader<T>::clear() {
    //删除所有结点
    while (headerNode->next != headerNode) {
    chainNode<T>* deleteNode = headerNode->next;
    headerNode->next = deleteNode->next;
    deleteNode->next->previous = headerNode;
    delete deleteNode;
    }
    listSize = 0;
    }

    //删索引fromIndex至toIndex之间的元素
    template <class T>
    void doublyLinkedListWithHeader<T>::removeRange(int fromIndex, int toIndex) {
    //确定索引是否有效
    if(fromIndex < 0 || toIndex >= listSize){
    //无效的索引
    std::ostringstream s;
    s << "Index from" << fromIndex << " to " << toIndex << " size = " << listSize;
    throw illegalParameterValue(s.str());
    }
    //从左往右更快找到被删除结点
    if (fromIndex < (listSize - toIndex - 1)) {
    //找到需要删除的起始结点的前驱
    chainNode<T>* p = headerNode;
    for(int i = 0; i < fromIndex; ++i)
    p = p->next;
    //开始删除结点
    for(int i = fromIndex; i <= toIndex; ++i){
    chainNode<T>* deleteNode = p->next;
    p->next = deleteNode->next;
    deleteNode->next->previous = p;
    delete deleteNode;
    }
    } else {
    //从右往左更快找到被删除结点
    //找到需要删除的起始结点的后继
    chainNode<T>* p = headerNode;
    for(int i = listSize - 1; i > toIndex; --i)
    p = p->previous;
    //开始删除结点
    for(int i = toIndex; i >= fromIndex; --i){
    chainNode<T>* deleteNode = p->previous;
    p->previous = deleteNode->previous;
    deleteNode->previous->next = p;
    delete deleteNode;
    }
    }
    listSize -= (toIndex - fromIndex + 1);
    }

    //判断*this是否和theList相等
    template <class T>
    bool doublyLinkedListWithHeader<T>::isEqual(const doublyLinkedListWithHeader<T> &theList) const {
    //同一个表,直接返回true
    if(this == &theList)
    return true;
    //长度不等,直接返回false
    if(listSize != theList.listSize)
    return false;

    //从两个方向开始比较
    chainNode<T> *currentFirst = headerNode->next, *currentEnd = headerNode->previous;
    chainNode<T> *anotherFirst = theList.headerNode->next, *anotherEnd = theList.headerNode->previous;
    while (currentFirst != currentEnd){
    //遇到不等的元素
    if(currentFirst->element != anotherFirst->element)
    return false;
    if(currentEnd->element != anotherEnd->element)
    return false;
    currentFirst = currentFirst->next;
    currentEnd = currentEnd->previous;
    anotherFirst = anotherFirst->next;
    anotherEnd = anotherEnd->previous;
    }
    return (currentFirst->element == anotherFirst->element);
    }

    //重载==运算符
    template <class T>
    bool operator==(const doublyLinkedListWithHeader<T> &theLeftList, const doublyLinkedListWithHeader<T> &theRightList){
    return theLeftList.isEqual(theRightList);
    }

    //判断*this是否小于theList
    template <class T>
    bool doublyLinkedListWithHeader<T>::isLess(const doublyLinkedListWithHeader<T> &theList) const {
    //是同一个线性表
    if(this == &theList)
    return false;

    //比较每一个元素
    chainNode<T> *p = headerNode->next, *q = theList.headerNode->next;
    while(p != headerNode && q != theList.headerNode){
    //当前线性表的元素更小
    if(p->element < q->element)
    return true;
    else if(p->element > q->element)
    //当前线性表的元素更大
    return false;
    p = p->next;
    q = q->next;
    }

    //当前线性表的长度更小
    if(p == NULL && q != NULL)
    return true;
    else
    return false;
    }

    //重载<运算符
    template <class T>
    bool operator<(const doublyLinkedListWithHeader<T> &theLeftList, const doublyLinkedListWithHeader<T> &theRightList){
    return theLeftList.isLess(theRightList);
    }

    #endif //TESTLIST_TESTLIST_H

3.和list容器做一些性能对比

  • 我简单的针对push_back迭代器pop_backsizeof对list和我自己实现的链表进行了性能对比。

    我的测试代码如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    #include <iostream>
    #include <list>
    #include "testList.h"
    using namespace std;
    int main(){
    clock_t start, finish;
    start = clock();
    doublyLinkedListWithHeader<int> nums1;
    for(int i = 0; i < 1000000; ++i)
    nums1.push_back(i);
    finish = clock();
    cout << "我的容器使用push_back插入1百万个整数的用时: " << (double)(finish - start) / CLOCKS_PER_SEC << " s" << endl;

    start = clock();
    list<int> nums2;
    for(int i = 0; i < 1000000; ++i)
    nums2.push_back(i);
    finish = clock();
    cout << "STL的list容器使用push_back插入1百万个整数的用时: " << (double)(finish - start) / CLOCKS_PER_SEC << " s" << endl;

    start = clock();
    for(auto it = nums1.begin(); it != nums1.end(); ++it);
    finish = clock();
    cout << "我的容器使用迭代器访问所有元素的用时: " << (double)(finish - start) / CLOCKS_PER_SEC << " s" << endl;

    start = clock();
    for(auto it = nums2.begin(); it != nums2.end(); ++it);
    finish = clock();
    cout << "STL的list容器使用迭代器访问所有元素的用时: " << (double)(finish - start) / CLOCKS_PER_SEC << " s" << endl;

    start = clock();
    for(int i = 0; i < 1000000; ++i)
    nums1.pop_back();
    finish = clock();
    cout << "我的容器使用pop_back弹出所有元素的用时: " << (double)(finish - start) / CLOCKS_PER_SEC << " s" << endl;

    start = clock();
    for(int i = 0; i < 1000000; ++i)
    nums2.pop_back();
    finish = clock();
    cout << "STL的list容器使用pop_back弹出所有元素的用时: " << (double)(finish - start) / CLOCKS_PER_SEC << " s" << endl;

    cout << "我的容器所占的空间字节数: " << sizeof(nums1) << "B" << endl;
    cout << "STL的list容器所占的空间字节数: " << sizeof(nums2) << "B" << endl;
    return 0;
    }
  • 运行结果如下

    可以发现我自己实现的链表在运行速度和空间消耗上都比list要优秀。

------------- 本文结束 感谢您的阅读 -------------

本文标题:STL容器list的底层实现---带头结点的双向循环链表

文章作者:Perry

发布时间:2019年10月22日 - 22:14

最后更新:2019年10月23日 - 00:18

原始链接:https://perry96.com/archives/637539e8.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%