views:

137

answers:

4

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.

+8  A: 

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.

GMan
+1 - *unless it is the head or tail of the list.* - It's also O(1) to find the second position in the list. And the third position....
Mark Byers
And by induction, it is O(1) to find position n in the list... heywaitaminute! :p
Edmund
+1  A: 

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.

Jon Skeet
+2  A: 

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.

IVlad
A: 

wt is the time complexity of stack insertion and queue deletion of elements

sangeeta