STL数据结构之List
1: List节点结构
list的总体结构是一个带头循环双向链表。看下图
List概览

template <class T>
struct __list_node {
typedef void* void_pointer;
void_pointer next;
void_pointer prev;
T data;
};
- 这个是在stl3.0版本下的list的节点的定义。
- 节点里面有一个前指针,一个后指针,有一个数据data。
- 这里只能知道他是一个双向链表。
💚💚💚💚💚💚💚💚💚💚💚💚💚💚💚💚💚
我们看一下它的构造函数。
class list --> list() { empty_initialize(); }
void empty_initialize() {
node = get_node();
node->next = node;
node->prev = node;
}
综上:list的总体结构是一个带头循环双向链表。
List迭代器

迭代器通常是怎么使用的,看一下下面这段代码。
int main()
{
list<int> l;
l.push_back(1);
l.push_back(2);
l.push_back(3);
l.push_back(4);
l.push_back(5);
l.push_back(6);
list<int>::iterator it = l.begin();
while (it != l.end())
{
cout << *it << " ";
it++;
}
cout << endl;
return 0;
}
- 我们从list< int >当中定义一个iterator对象,然后让他去访问我们的节点
- 并且他所支持的操作有++,解引用,当然还有 - -
stl3.0当中的迭代器实现:
template<class T, class Ref, class Ptr>
struct __list_iterator {
typedef __list_iterator<T, T&, T*> iterator;
typedef __list_iterator<T, const T&, const T*> const_iterator;
typedef __list_iterator<T, Ref, Ptr> self;
typedef bidirectional_iterator_tag iterator_category;
typedef T value_type;
typedef Ptr pointer;
typedef Ref reference;
typedef __list_node<T>* link_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
link_type node;
__list_iterator(link_type x) : node(x) {}
__list_iterator() {}
__list_iterator(const iterator& x) : node(x.node) {}
bool operator==(const self& x) const { return node == x.node; }
bool operator!=(const self& x) const { return node != x.node; }
reference operator*() const { return (*node).data; }
#ifndef __SGI_STL_NO_ARROW_OPERATOR
pointer operator->() const { return &(operator*()); }
#endif /* __SGI_STL_NO_ARROW_OPERATOR */
self& operator++() {
node = (link_type)((*node).next);
return *this;
}
self operator++(int) {
self tmp = *this;
++*this;
return tmp;
}
self& operator--() {
node = (link_type)((*node).prev);
return *this;
}
self operator--(int) {
self tmp = *this;
--*this;
return tmp;
}

文章介绍了STL中的List数据结构,它是一个带头循环双向链表。每个节点包含一个前指针、一个后指针和数据。接着,文章展示了List迭代器的使用,包括如何通过迭代器遍历列表并执行操作,如++、解引用等。同时,提供了迭代器的实现细节。

2142

被折叠的 条评论
为什么被折叠?



