Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::list::reverse have O(n) complexity?

Why does the reverse function for the std::list class in the C++ standard library have linear runtime? I would think that for doubly-linked lists the reverse function should have been O(1).

Reversing a doubly-linked list should just involve switching the head and the tail pointers.

like image 819
Curious Avatar asked Feb 24 '16 20:02

Curious


People also ask

What is the time complexity of reversing a list?

The time complexity of the reverse() operation is O(n) for a list with n elements. The standard Python implementation cPython “touches” all elements in the original list to move them to another position. Thus, the time complexity is linear in the number of list elements.

What is the time complexity of reverse function in C++?

reverse() is a predefined function in header file algorithm. It is defined as a template in the above mentioned header file. It reverses the order of the elements in the range [first, last) of any container. The time complexity is O(n).

What does std :: reverse do?

std::reverse() is a built-in function in C++'s Standard Template Library. The function takes in a beginning iterator, an ending iterator, and reverses the order of the element in the given range.

Is there any reverse function in C++?

C++ Algorithm reverse() function is used to reverse the order of the elements within a range [first, last).


1 Answers

Hypothetically, reverse could have been O(1). There (again hypothetically) could have been a boolean list member indicating whether the direction of the linked list is currently the same or opposite as the original one where the list was created.

Unfortunately, that would reduce the performance of basically any other operation (albeit without changing the asymptotic runtime). In each operation, a boolean would need to be consulted to consider whether to follow a "next" or "prev" pointer of a link.

Since this was presumably considered a relatively infrequent operation, the standard (which does not dictate implementations, only complexity), specified that the complexity could be linear. This allows "next" pointers to always mean the same direction unambiguously, speeding up common-case operations.

like image 165
Ami Tavory Avatar answered Oct 26 '22 00:10

Ami Tavory