实现forward_list后的剪接

Splice_after implementation of forward_list

本文关键字:list forward 实现      更新时间:2023-10-16

forward_list中有一个函数splice_after(供参考),特别是给定链接中的函数#3。考虑到list是单独连接的,如何实现呢。

作为练习,当我实现它时,我必须迭代列表,直到我到达first之前的节点(这样我就可以将first连接到last),然后再次迭代,直到我达到last之前的节点为止(这样我可以将当前列表的节点连接到last之前的节点)。这对我来说似乎并不高效,我想知道是否有更好的方法可以在不迭代的情况下做到这一点?

我怀疑您误读了有点微妙的范围规范,该规范说"(first,last)"被移动,而不是"[first,last)"(注意左括号/括号)。也就是说,正如名称所示,拼接操作只在第一个对象之后开始。

该函数的实现实际上非常简单(如果忽略迭代器的常量以及它可能需要处理不同分配器的事实):

void splice_after(const_iterator pos, forward_list& other,
                  const_iterator first, const_iterator last) {
    node* f = first._Node->_Next;
    node* p = f;
    while (p->_Next != last._Node) { // last is not included: find its predecessor
        p = p->_Next;
    }
    first._Node->Next = last._Node;  // remove nodes from this
    p->_Next = pos._Node->_Next;     // hook the tail of the other list onto last
    pos._Node->_Next = f;            // hook the spliced elements onto pos
}

此操作具有线性复杂性,因为它需要找到last的前一个。

(社区维基,请投稿)

 A -> B -> C -> D -> E
           ^
           ^ pos points to C

other列表中

 U -> V -> W -> X -> Y -> Z
      ^              ^
      ^ first        ^ last

呼叫.splice(pos, other, first, last)

我们要把W和X排到最前面。即firstlast之间但不包括的所有内容。最终A->B->C->W->X->D->E位于顶部,U->V->Y->Z位于底部。

auto copy_of_first_next = first->next;
first->next = last;
// the `other` list has now been emptied
auto copy_of_pos_next = pos->next;
pos -> next = first;
while(first->next != last) ++first;
// `first` now points just before `last`
first->next = copy_of_pos_next