Is time complexity for insertion/deletion in a doubly linked list of order O(n)?

徘徊边缘 提交于 2019-12-01 02:59:56

问题


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.



来源:https://stackoverflow.com/questions/3899456/is-time-complexity-for-insertion-deletion-in-a-doubly-linked-list-of-order-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!