相較於vector的連續線性空間,list就顯得複雜許多,它的好處是每次插入或刪除一個元素,就配置或釋放一個元素空間。因此,list對於空間的運用有絕對的精準,一點也不浪費。而且,對於任何位置的元素插入或元素移除,list永遠是常數時間。
list不僅是一個雙向鏈表,而且還是一個環狀雙向鏈表。另外,還有一個重要性質,插入操作和接合操作都不會造成原有的list迭代器失效,這在vector是不成立的。因爲vector的插入操作可能造成記憶體重新配置,導致原有的迭代器全部失效。甚至list的元素刪除操作(erase),也只有“指向被刪除元素”的那個迭代器失效,其他迭代器不受任何影響。
以下是list的節點、迭代器數據結構設計以及list的源碼剖析:
list不僅是一個雙向鏈表,而且還是一個環狀雙向鏈表。另外,還有一個重要性質,插入操作和接合操作都不會造成原有的list迭代器失效,這在vector是不成立的。因爲vector的插入操作可能造成記憶體重新配置,導致原有的迭代器全部失效。甚至list的元素刪除操作(erase),也只有“指向被刪除元素”的那個迭代器失效,其他迭代器不受任何影響。
以下是list的節點、迭代器數據結構設計以及list的源碼剖析:
////////////////////////////////////////////////////////////////////////////////
// list結點, 提供雙向訪問能力
////////////////////////////////////////////////////////////////////////////////
// -------- -------- -------- --------
// | next |---------->| next |---------->| next |---------->| next |
// -------- -------- -------- --------
// | prev |<----------| prev |<----------| prev |<----------| prev |
// -------- -------- -------- --------
// | data | | data | | data | | data |
// -------- -------- -------- --------
////////////////////////////////////////////////////////////////////////////////
template <class T>
struct __list_node
{
typedef void* void_pointer;
void_pointer next;
void_pointer prev;
T data;
};
// 至於爲什麼不使用默認參數, 這個是因爲有一些編譯器不能提供推導能力,
// 而作者又不想維護兩份代碼, 故不使用默認參數
template<class T, class Ref, class Ptr>
struct __list_iterator
{
typedef __list_iterator<T, T&, T*> iterator; // STL標準強制要求
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的節點
__list_iterator(link_type x) : node(x) {}
__list_iterator() {}
__list_iterator(const iterator& x) : node(x.node) {}
// 在STL算法中需要迭代器提供支持
bool operator==(const self& x) const { return node == x.node; }
bool operator!=(const self& x) const { return node != x.node; }
// 以下對迭代器取值(dereference),取的是節點的數據值
reference operator*() const { return (*node).data; }
// 以下是迭代器的成員存取運算子的標準做法
pointer operator->() const { return &(operator*()); }
// 前綴自加,對迭代器累加1,就是前進一個節點
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;
}
};
////////////////////////////////////////////////////////////////////////////////
// list不僅是個雙向鏈表, 而且還是一個環狀雙向鏈表
////////////////////////////////////////////////////////////////////////////////
// end() 頭結點 begin()
// ↓ ↓ ↓
// -------- -------- -------- --------
// ---->| next |---------->| next |---------->| next |---------->| next |------
// | -------- -------- -------- -------- |
// | --| prev |<----------| prev |<----------| prev |<----------| prev |<--| |
// | | -------- -------- -------- -------- | |
// | | | data | | data | | data | | data | | |
// | | -------- -------- -------- -------- | |
// | | | |
// | | -------- -------- -------- -------- | |
// ---|-| next |<----------| next |<----------| next |<----------| next |<--|--
// | -------- -------- -------- -------- |
// ->| prev |---------->| prev |---------->| prev |---------->| prev |----
// -------- -------- -------- --------
// | data | | data | | data | | data |
// -------- -------- -------- --------
////////////////////////////////////////////////////////////////////////////////
// 默認allocator爲alloc, 其具體使用版本請參照<stl_alloc.h>
template <class T, class Alloc = alloc>
class list
{
protected:
typedef void* void_pointer;
typedef __list_node<T> list_node;
// 專屬之空間配置器,每次配置一個節點大小
typedef simple_alloc<list_node, Alloc> list_node_allocator;
public:
typedef T value_type;
typedef value_type* pointer;
typedef value_type& reference;
typedef list_node* link_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef __list_iterator<T, T&, T*> iterator;
protected:
link_type node ; // 只要一個指針,便可表示整個環狀雙向鏈表
// 分配一個新結點, 注意這裏並不進行構造,
// 構造交給全局的construct, 見<stl_stl_uninitialized.h>
link_type get_node() { return list_node_allocator::allocate(); }
// 釋放指定結點, 不進行析構, 析構交給全局的destroy
void put_node(link_type p) { list_node_allocator::deallocate(p); }
// 產生(配置並構造)一個節點, 首先分配內存, 然後進行構造
// 注: commit or rollback
link_type create_node(const T& x)
{
link_type p = get_node();
construct(&p->data, x);
return p;
}
// 析構結點元素, 並釋放內存
void destroy_node(link_type p)
{
destroy(&p->data);
put_node(p);
}
protected:
// 用於空鏈表的建立
void empty_initialize()
{
node = get_node(); // 配置一個節點空間,令node指向它
node->next = node; // 令node頭尾都指向自己,不設元素值
node->prev = node;
}
// 創建值爲value共n個結點的鏈表
// 注: commit or rollback
void fill_initialize(size_type n, const T& value)
{
empty_initialize();
__STL_TRY
{
// 此處插入操作時間複雜度O(1)
insert(begin(), n, value);
}
__STL_UNWIND(clear(); put_node(node));
}
public:
list() { empty_initialize(); }
iterator begin() { return (link_type)((*node).next); }
// 鏈表成環, 當指所以頭節點也就是end
iterator end() { return node; }
// 頭結點指向自身說明鏈表中無元素
bool empty() const { return node->next == node; }
// 使用全局函數distance()進行計算, 時間複雜度O(n)
size_type size() const
{
size_type result = 0;
distance(begin(), end(), result);
return result;
}
size_type max_size() const { return size_type(-1); }
reference front() { return *begin(); }
reference back() { return *(--end()); }
////////////////////////////////////////////////////////////////////////////////
// 在指定位置插入元素
////////////////////////////////////////////////////////////////////////////////
// insert(iterator position, const T& x)
// ↓
// create_node(x)
// p = get_node();-------->list_node_allocator::allocate();
// construct(&p->data, x);
// ↓
// tmp->next = position.node;
// tmp->prev = position.node->prev;
// (link_type(position.node->prev))->next = tmp;
// position.node->prev = tmp;
////////////////////////////////////////////////////////////////////////////////
iterator insert(iterator position, const T& x)
{
link_type tmp = create_node(x); // 產生一個節點
// 調整雙向指針,使tmp插入進去
tmp->next = position.node;
tmp->prev = position.node->prev;
(link_type(position.node->prev))->next = tmp;
position.node->prev = tmp;
return tmp;
}
// 指定位置插入n個值爲x的元素, 詳細解析見實現部分
void insert(iterator pos, size_type n, const T& x);
void insert(iterator pos, int n, const T& x)
{
insert(pos, (size_type)n, x);
}
void insert(iterator pos, long n, const T& x)
{
insert(pos, (size_type)n, x);
}
// 在鏈表前端插入結點
void push_front(const T& x) { insert(begin(), x); }
// 在鏈表最後插入結點
void push_back(const T& x) { insert(end(), x); }
// 移除迭代器position所指節點
iterator erase(iterator position)
{
link_type next_node = link_type(position.node->next);
link_type prev_node = link_type(position.node->prev);
prev_node->next = next_node;
next_node->prev = prev_node;
destroy_node(position.node);
return iterator(next_node);
}
// 擦除一個區間的結點, 詳細解析見實現部分
iterator erase(iterator first, iterator last);
void resize(size_type new_size, const T& x);
void resize(size_type new_size) { resize(new_size, T()); }
void clear();
// 刪除鏈表第一個結點
void pop_front() { erase(begin()); }
// 刪除鏈表最後一個結點
void pop_back()
{
iterator tmp = end();
erase(--tmp);
}
list(size_type n, const T& value) { fill_initialize(n, value); }
list(int n, const T& value) { fill_initialize(n, value); }
list(long n, const T& value) { fill_initialize(n, value); }
~list()
{
// 釋放所有結點 // 使用全局函數distance()進行計算, 時間複雜度O(n)
size_type size() const
{
size_type result = 0;
distance(begin(), end(), result);
return result;
}
clear();
// 釋放頭結點
put_node(node);
}
list<T, Alloc>& operator=(const list<T, Alloc>& x);
protected:
////////////////////////////////////////////////////////////////////////////////
// 將[first, last)內的所有元素移動到position之前
// 如果last == position, 則相當於鏈表不變化, 不進行操作
////////////////////////////////////////////////////////////////////////////////
// 初始狀態
// first last
// ↓ ↓
// -------- -------- -------- -------- -------- --------
// | next |-->| next |-->| next | | next |-->| next |-->| next |
// ... -------- -------- -------- ... -------- -------- -------- ...
// | prev |<--| prev |<--| prev | | prev |<--| prev |<--| prev |
// -------- -------- -------- -------- -------- --------
//
// position
// ↓
// -------- -------- -------- -------- -------- --------
// | next |-->| next |-->| next |-->| next |-->| next |-->| next |
// ... -------- -------- -------- -------- -------- -------- ...
// | prev |<--| prev |<--| prev |<--| prev |<--| prev |<--| prev |
// -------- -------- -------- -------- -------- --------
//
// 操作完成後狀態
// first
// |
// --------------|--------------------------------------
// | ------------|------------------------------------ | last
// | | ↓ | | ↓
// -------- | | -------- -------- -------- | | -------- --------
// | next |-- | ----->| next |-->| next | | next |----- | -->| next |-->| next |
// ... -------- | | -------- -------- ... -------- | | -------- -------- ...
// | prev |<--- | ---| prev |<--| prev | | prev |<-- | -----| prev |<--| prev |
// -------- | | -------- -------- -------- | | -------- --------
// | | | |
// | ------ | |
// ------- | ------------------------------ |
// | | | |
// | | | -----------------------------
// | | | |
// | | | | position
// | | | | ↓
// -------- -------- | | | | -------- -------- -------- --------
// | next |-->| next |-- | | -->| next |-->| next |-->| next |-->| next |
// ... -------- -------- | | -------- -------- -------- -------- ...
// | prev |<--| prev |<--- ------| prev |<--| prev |<--| prev |<--| prev |
// -------- -------- -------- -------- -------- --------
////////////////////////////////////////////////////////////////////////////////
void transfer(iterator position, iterator first, iterator last)
{
if (position != last) // 如果last == position, 則相當於鏈表不變化, 不進行操作
{
(*(link_type((*last.node).prev))).next = position.node;
(*(link_type((*first.node).prev))).next = last.node;
(*(link_type((*position.node).prev))).next = first.node;
link_type tmp = link_type((*position.node).prev);
(*position.node).prev = (*last.node).prev;
(*last.node).prev = (*first.node).prev;
(*first.node).prev = tmp;
}
}
public:
// 將鏈表x移動到position所指位置之前
void splice(iterator position, list& x)
{
if (!x.empty())
transfer(position, x.begin(), x.end());
}
// 將鏈表中i指向的內容移動到position之前
void splice(iterator position, list&, iterator i)
{
iterator j = i;
++j;
if (position == i || position == j) return;
transfer(position, i, j);
}
// 將[first, last}元素移動到position之前
void splice(iterator position, list&, iterator first, iterator last)
{
if (first != last)
transfer(position, first, last);
}
void remove(const T& value);
void unique();
void merge(list& x);
void reverse();
void sort();
};
// 銷燬所有結點, 將鏈表置空
template <class T, class Alloc>
void list<T, Alloc>::clear()
{
link_type cur = (link_type) node->next;
while (cur != node)
{
link_type tmp = cur;
cur = (link_type) cur->next;
destroy_node(tmp);
}
// 恢復node原始狀態
node->next = node;
node->prev = node;
}
// 鏈表賦值操作
// 如果當前容器元素少於x容器, 則析構多餘元素,
// 否則將調用insert插入x中剩餘的元素
template <class T, class Alloc>
list<T, Alloc>& list<T, Alloc>::operator=(const list<T, Alloc>& x)
{
if (this != &x)
{
iterator first1 = begin();
iterator last1 = end();
const_iterator first2 = x.begin();
const_iterator last2 = x.end();
while (first1 != last1 && first2 != last2) *first1++ = *first2++;
if (first2 == last2)
erase(first1, last1);
else
insert(last1, first2, last2);
}
return *this;
}
// 移除容器內所有的相鄰的重複結點
// 時間複雜度O(n)
// 用戶自定義數據類型需要提供operator ==()重載
template <class T, class Alloc>
void list<T, Alloc>::unique()
{
iterator first = begin();
iterator last = end();
if (first == last) return;
iterator next = first;
while (++next != last)
{
if (*first == *next)
erase(next);
else
first = next;
next = first;
}
}
// 假設當前容器和x都已序, 保證兩容器合併後仍然有序
template <class T, class Alloc>
void list<T, Alloc>::merge(list<T, Alloc>& x)
{
iterator first1 = begin();
iterator last1 = end();
iterator first2 = x.begin();
iterator last2 = x.end();
// 注意:前提是,兩個lists都已經遞增排序
while (first1 != last1 && first2 != last2)
if (*first2 < *first1)
{
iterator next = first2;
transfer(first1, first2, ++next);
first2 = next;
}
else
++first1;
if (first2 != last2)
transfer(last1, first2, last2);
}