以下对迁移操作transfer()进行分析,该函数不是公共接口,属于list容器的保护成员函数,但是它为拼接函数服务,拼接函数的核心就是迁移函数;transfer()和splice()函数
- protected:
- //把区间[first,last)的节点数据插入到指定节点position之前,position不能在区间内部
- //这个函数是list类的protected属性,不是公共接口,只为list类成员服务
- //为下面拼接函数void splice()服务
- void transfer(iterator __position, iterator __first, iterator __last) {
- if (__position != __last) {
- // Remove [first, last) from its old position.
- __last._M_node->_M_prev->_M_next = __position._M_node;
- __first._M_node->_M_prev->_M_next = __last._M_node;
- __position._M_node->_M_prev->_M_next = __first._M_node;
- // Splice [first, last) into its new position.
- _List_node_base* __tmp = __position._M_node->_M_prev;
- __position._M_node->_M_prev = __last._M_node->_M_prev;
- __last._M_node->_M_prev = __first._M_node->_M_prev;
- __first._M_node->_M_prev = __tmp;
- }
- }
- public:
- //**********************************************************
- //*******************拼接操作对外接口***********************
- //把链表拼接到当前链表指定位置position之前
- /*void splice(const_iterator pos, list& other);
- //把it在链表other所指的位置拼接到当前链表pos之前,it和pos可指向同一链表
- void splice(const_iterator pos, list& other, const_iterator it);
- //把链表other的节点范围[first,last)拼接在当前链表所指定的位置pos之前
- //[first,last)和pos可指向同一链表
- void splice(const_iterator pos, list& other,
- const_iterator first, const_iterator last);
- *************************************************************/
- //**********************************************************
- //将链表x拼接到当前链表的指定位置position之前
- //这里x和*this必须不同,即是两个不同的链表
- void splice(iterator __position, list& __x) {
- if (!__x.empty())
- this->transfer(__position, __x.begin(), __x.end());
- }
- //将i所指向的节点拼接到position所指位置之前
- //注意:i和position可以指向同一个链表
- void splice(iterator __position, list&, iterator __i) {
- iterator __j = __i;
- ++__j;
- //若i和position指向同一个链表,且指向同一位置
- //或者i和position指向同一个链表,且就在position的直接前驱位置
- //针对以上这两种情况,不做任何操作
- if (__position == __i || __position == __j) return;
- //否则,进行拼接操作
- this->transfer(__position, __i, __j);
- }
- //将范围[first,last)内所有节点拼接到position所指位置之前
- //注意:[first,last)和position可指向同一个链表,
- //但是position不能在[first,last)范围之内
- void splice(iterator __position, list&, iterator __first, iterator __last) {
- if (__first != __last)
- this->transfer(__position, __first, __last);
- }
merge函数
<span style="font-size:14px;">template<class T, class Alloc>
void list<T,Alloc>::merge(list<T,Alloc>&x)
{
iterator first1 = begin();
iterator last1 = end();
iterator first2 = begin();
iterator last2 = end();
//<前提是两个序列都已经排序完成了
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);
}
}
}</span>
template<class T, class Alloc>
void list<T,Alloc>::reverse()
{
if (node->next == node || link_type(node->next->next == node))
{
return;
}
iterator first = begin();
++first;
while (first != end())
{
iterator old = first;
++first;
transfer(begin(),old,first);
}
}