Is time complexity for insertion/deletion in a dou

2019-02-17 14:37发布

问题:

To insert/delete a node with a particular value in DLL (doubly linked list) entire list need to be traversed to find the location hence these operations should be O(n).

If that's the case then how come STL list (most likely implemented using DLL) is able to provide these operations in constant time?

Thanks everyone for making it clear to me.

回答1:

Insertion and deletion at a known position is O(1). However, finding that position is O(n), unless it is the head or tail of the list.

When we talk about insertion and deletion complexity, we generally assume we already know where that's going to occur.



回答2:

It's not. The STL methods take an iterator to the position where insertion is to happen, so strictly speaking, they ARE O(1), because you're giving them the position. You still have to find the position yourself in O(n) however.



回答3:

Deleting an arbitrary value (rather than a node) will indeed be O(n) as it will need to find the value. Deleting a node (i.e. when you start off knowing the node) is O(1).

Inserting based on the value - e.g. inserting in a sorted list - will be O(n). If you're inserting after or before an existing known node is O(1).

Inserting to the head or tail of the list will always be O(1) - because those are just special cases of the above.