O(n)中的C ++拆分列表而不是O(1)

时间:2016-11-30 21:01:43

标签: c++ list time-complexity

我在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 };
    }

1 个答案:

答案 0 :(得分:1)

我发现了问题。 std::pair创建了我正在返回的两个列表的副本,这就是线性时间。当我std::move列出该对时,它会在我分裂的时间内运行。