我在c ++中实现列表,我对split方法的复杂性有疑问。而不是时间复杂度,我的复杂性是线性的(O(n))。这是我的代码:
/*
* Destructively splits the list into the two that are returned.
* The first list consists of elements formerly in the [begin, place) range.
* The second list consists of elements formerly in the [place, end) range.
*/
std::pair<list, list> list::split(list::const_iterator place) {
list first_list{}, second_list{};
if (head == nullptr) {
return{ first_list, second_list };
}
if (head == place.current_ptr) {
swap(second_list);
return{ first_list, second_list };
}
if (place.current_ptr == nullptr) {
swap(first_list);
return{ first_list, second_list };
}
first_list.head = head;
first_list.num_elements = std::distance(cbegin(), place);
first_list.tail = place.current_ptr->prev;
second_list.head = place.current_ptr;
if (second_list.head == nullptr) {
second_list.tail = nullptr;
}
else
{
second_list.head->prev = nullptr;
second_list.tail = tail;
}
second_list.num_elements = num_elements - first_list.num_elements;
first_list.tail->next = nullptr;
tail = head = nullptr;
num_elements = 0;
return{ first_list, second_list };
}
答案 0 :(得分:1)
我发现了问题。 std::pair
创建了我正在返回的两个列表的副本,这就是线性时间。当我std::move
列出该对时,它会在我分裂的时间内运行。