一、链表
1.1 什么是List?
在C语言中,我们需要使用结构体struct来进行List(链表)的实现:
cpp
struct ListNode
{
DataType Data;//DataType是任意类型的变量定义
struct ListNode* next;//指向下一个结点的指针变量
};
与之前的vector不一样,List的存储是随机存储,不是一段的连续的空间,既然不是一段连续的空间,那就不能使用下标进行访问。在C++中可以直接使用list容器:
列表是序列容器,允许对序列中任意位置的恒定时间插入和擦除作,以及双向迭代。
1.2 list的构造
与vector一样,list的构造函数也是四个:

cpp
list<int> l1; // 构造空的l1
list<int> l2(4, 100); // l2中放4个值为100的元素
list<int> l3(l2.begin(), l2.end()); // 用l2的[begin(), end())左闭右开的区间构造l3
list<int> l4(l3); // 用l3拷贝构造l4
1.3 list的iterator的使用
在不清楚迭代器的本质之前,我们可以把迭代器看做一个指针,该指针指向list中的某个结点。
**begin():**返回一个迭代器,该迭代器指向列表容器中的第一个元素。

end(): 返回最后一个元素下一个位置的迭代器
迭代器的使用可以快速访问某个结点,begin与end为正向迭代器,对迭代器执行++操作,迭代器向后移动:
cpp
list<int> l5 = { 1,2,3,4,5 };
list<int>::iterator it = l5.begin();
while (it != l5.end())
{
cout << *it << " ";
++it;
}
cout << endl;
// C++11范围for的方式遍历
for (auto& e : l5)
cout << e << " ";
cout << endl;

1.4 List中接口说明
1.4.1 容量(capacity)
**empty():**判断是否为空,即list是否为空:
cpp
list<int> l5 = { 1,2,3,4,5 };
list<int>::iterator it = l5.begin();
while (! l5.empty())
{
cout << l5.front() << " ";
l5.pop_front();
}
cout << endl;
**size():**返回list中有效节点的数量:
cpp
list<int> l5 = { 1,2,3,4,5 };
cout << l5.size() << endl;

1.4.2 list element access
**front():**返回list的第一个节点中值的引用:
cpp
list<int> l5 = { 1,2,3,4,5 };
cout << l5.front() << endl;

**back():**返回list的最后一个节点中值的引用:
cpp
list<int> l5 = { 1,2,3,4,5 };
cout << l5.back() << endl;

1.4.3 list modifiers
**push_front():**在list首元素前插入值为val的元素:

**pop_front():**删除list中第一个元素:

**push_back():**在list尾部插入值为val的元素:

**pop_back():**删除list中最后一个元素:

**insert():**在list position 位置中插入值为val的元素:

cpp
list<int> l5 = { 1,2,3,4,5 };
//inster(8,l5.begin());
auto it = l5.begin();
++it; // it points now to number 2
l5.insert(it, 10); // 1 10 2 3 4 5
// "it" still points to number 2
l5.insert(it, 2, 20); //1 10 20 20 2 3 4 5
插入时可以使用迭代器来进行位置插入,有三个构造函数:
cpp
l5.insert(it, 10); // 在该位置插入一个
l5.insert(it, 2, 20); // 在该位置插入多个
std::vector<int> myvector(2, 30);
l5.insert(it, myvector.begin(), myvector.end());//在该位置插入另一种结构的迭代器
**erase():**删除list position位置的元素:

1.5 迭代器失效问题
前面说过,此处大家可将迭代器暂时理解成类似于指针,迭代器失效即迭代器所指向的节点的无 效,即该节点被删除了。因为list的底层结构为带头结点的双向循环链表,因此在list中进行插入时是不会导致list的迭代器失效的,只有在删除时才会失效,并且失效的只是指向被删除节点的迭代器,其他迭代器不会受到影响。
cpp
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
list<int> l(array, array + sizeof(array) / sizeof(array[0]));
auto it = l.begin();
while (it != l.end())
{
// erase()函数执行后,it所指向的节点已被删除,因此it无效,在下一次使用it时,必须先给
//其赋值
l.erase(it);
++it;
}
改正:
cpp
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
list<int> l(array, array+sizeof(array)/sizeof(array[0]));
auto it = l.begin();
while (it != l.end())
{
l.erase(it++); // it = l.erase(it);
}
1.6 list解释
所学的list底层是一个双向带头循环的链表,如图:

1.7 list与vector的对比
下去我们需要模拟实现list哦,需要明白底层原理,可以让我们更加清楚的使用容器。
